use std::io::Cursor;

use binrw::{BinRead, BinWrite};
use diff::Diff;
use ezcad::array_of::ArrayOf;

#[test]
fn array_of_be() {
    let encoded: Vec<u8> = vec![
        0x00, 0x00, 0x00, 0x02, 0x0A, 0x0B, 0x0C, 0x0D, 0x01, 0x02, 0x03, 0x04,
    ];
    let decoded: ArrayOf<u32> = ArrayOf::from(vec![0x0A0B0C0D, 0x01020304]);
    let mut stream: Cursor<Vec<u8>> = Cursor::new(encoded.clone());
    assert_eq!(ArrayOf::<u32>::read_be(&mut stream).unwrap(), decoded);

    let mut buffer: Cursor<Vec<u8>> = Cursor::new(vec![]);
    decoded.write_be(&mut buffer).unwrap();
    assert_eq!(buffer.into_inner(), encoded);
}

#[test]
fn array_of_le() {
    let encoded: Vec<u8> = vec![
        0x02, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x01, 0x02, 0x03, 0x04,
    ];
    let decoded: ArrayOf<u32> = ArrayOf::from(vec![0x0D0C0B0A, 0x04030201]);
    let mut stream: Cursor<Vec<u8>> = Cursor::new(encoded.clone());
    assert_eq!(ArrayOf::<u32>::read_le(&mut stream).unwrap(), decoded);

    let mut buffer: Cursor<Vec<u8>> = Cursor::new(vec![]);
    decoded.write_le(&mut buffer).unwrap();
    assert_eq!(buffer.into_inner(), encoded);
}

#[test]
fn array_of_struct() {
    #[derive(BinRead, BinWrite, Debug, PartialEq, Default, Diff)]
    #[diff(attr(
        #[derive(Debug, PartialEq)]
    ))]
    struct Test {
        a: u16,
        b: u16,
    }

    let encoded: Vec<u8> = vec![
        0x00, 0x00, 0x00, 0x02, 0x0A, 0x0B, 0x0C, 0x0D, 0x01, 0x02, 0x03, 0x04,
    ];
    let decoded: ArrayOf<Test> = ArrayOf::from(vec![
        Test {
            a: 0x0A0B,
            b: 0x0C0D,
        },
        Test {
            a: 0x0102,
            b: 0x0304,
        },
    ]);

    let mut stream: Cursor<Vec<u8>> = Cursor::new(encoded.clone());
    assert_eq!(ArrayOf::<Test>::read_be(&mut stream).unwrap(), decoded);

    let mut buffer: Cursor<Vec<u8>> = Cursor::new(vec![]);
    decoded.write_be(&mut buffer).unwrap();
    assert_eq!(buffer.into_inner(), encoded);
}
