#[allow(dead_code, unused_imports)]
mod monster_generated;

use flatbuffers::FlatBufferBuilder;
use monster_generated::my_game::sample::Monster;
use monster_generated::my_game::sample::MonsterArgs;

// https://github.com/frol/flatc-rust/blob/master/examples/tutorial/src/main.rs
fn main() {
    let mut fbb = FlatBufferBuilder::new();

    let name = fbb.create_string("Sample Name!");

    let monster = Monster::create(&mut fbb, &MonsterArgs {
        mana: 150,
        hp: 80,
        name: Some(name),
        ..Default::default()
    });

    fbb.finish(monster, None);

    let buff = fbb.finished_data();

    println!("FlatBuffers: {}", hex::encode(&buff));

    let monster_2 = flatbuffers::get_root::<Monster>(&buff);
    println!("Monster hp: {}", monster_2.hp());
    println!("Monster name: {:?}", monster_2.name());

    let offset_to_body = u32::from_le_bytes(get_4bytes(&buff));
    println!("Offset to body  : {:>4}, hex: {}", offset_to_body, hex::encode(&get_4bytes(&buff)));
    let xx = &buff[4..offset_to_body as usize];
    println!("{}", hex::encode(xx));
    let offset_to_vtable = u32::from_le_bytes(get_4bytes(&buff[offset_to_body as usize..]));
    println!("Offset to vtable: {:>4}, hex: {}", offset_to_vtable, hex::encode(get_4bytes(&buff[offset_to_body as usize..])));

    let a1 = u16::from_le_bytes(get_2bytes(&buff[offset_to_body as usize..]));
    let a2 = u16::from_le_bytes(get_2bytes(&buff[(offset_to_body + 2) as usize..]));
    println!("a1: {}, a2: {}", a1, a2);
}

fn get_2bytes(buff: &[u8]) -> [u8; 2] {
    let mut ret = [0_u8; 2];
    ret[0] = buff[0];
    ret[1] = buff[1];
    ret
}

fn get_4bytes(buff: &[u8]) -> [u8; 4] {
    let mut ret = [0_u8; 4];
    ret[0] = buff[0];
    ret[1] = buff[1];
    ret[2] = buff[2];
    ret[3] = buff[3];
    ret
}
