// Copyright This program is released into the public domain.

#include <string>
#include <iostream>
#include <msgpack.hpp>
#include "./msgio.h"

int main(void) {
    msgpack::sbuffer buffer;

    msgpack::packer<msgpack::sbuffer> pk(&buffer);
    pk.pack_array(4);
    pk.pack(std::string("Log message ... 1"));
    pk.pack(std::string("Log message ... 2"));
    pk.pack(std::string("Log message ... 3"));
    pk.pack(2233);

    // save
    save_msgpack_sbuffer(buffer, __FILE__".msgpack");

    // use msgpack::unpacker to unpack multiple objects.
    msgpack::unpacker upk;

    // feeds the buffer.
    upk.reserve_buffer(buffer.size());
    memcpy(upk.buffer(), buffer.data(), buffer.size());
    upk.buffer_consumed(buffer.size());

    // // now starts streaming deserialization.
    msgpack::unpacked result;
    while (upk.next(&result)) {
        msgpack::object obj = result.get();
        if (obj.type != msgpack::type::ARRAY) {
            throw msgpack::type_error();
        }

        if (obj.via.array.size != 4) {
            throw msgpack::type_error();
        }

        std::cout << obj.via.array.ptr[0].as<std::string>() << std::endl;
        std::cout << obj.via.array.ptr[1].as<std::string>() << std::endl;
        std::cout << obj.via.array.ptr[2].as<std::string>() << std::endl;
        std::cout << obj.via.array.ptr[3].as<int>() << std::endl;

        std::cout << obj << std::endl;
    }
}