use std::io::{BufReader, BufWriter};

use super::*;

#[test]
fn test_handshake_message_server_key_exchange() -> Result<()> {
    let raw_server_key_exchange = vec![
        0x03, 0x00, 0x1d, 0x41, 0x04, 0x0c, 0xb9, 0xa3, 0xb9, 0x90, 0x71, 0x35, 0x4a, 0x08, 0x66,
        0xaf, 0xd6, 0x88, 0x58, 0x29, 0x69, 0x98, 0xf1, 0x87, 0x0f, 0xb5, 0xa8, 0xcd, 0x92, 0xf6,
        0x2b, 0x08, 0x0c, 0xd4, 0x16, 0x5b, 0xcc, 0x81, 0xf2, 0x58, 0x91, 0x8e, 0x62, 0xdf, 0xc1,
        0xec, 0x72, 0xe8, 0x47, 0x24, 0x42, 0x96, 0xb8, 0x7b, 0xee, 0xe7, 0x0d, 0xdc, 0x44, 0xec,
        0xf3, 0x97, 0x6b, 0x1b, 0x45, 0x28, 0xac, 0x3f, 0x35, 0x02, 0x03, 0x00, 0x47, 0x30, 0x45,
        0x02, 0x21, 0x00, 0xb2, 0x0b, 0x22, 0x95, 0x3d, 0x56, 0x57, 0x6a, 0x3f, 0x85, 0x30, 0x6f,
        0x55, 0xc3, 0xf4, 0x24, 0x1b, 0x21, 0x07, 0xe5, 0xdf, 0xba, 0x24, 0x02, 0x68, 0x95, 0x1f,
        0x6e, 0x13, 0xbd, 0x9f, 0xaa, 0x02, 0x20, 0x49, 0x9c, 0x9d, 0xdf, 0x84, 0x60, 0x33, 0x27,
        0x96, 0x9e, 0x58, 0x6d, 0x72, 0x13, 0xe7, 0x3a, 0xe8, 0xdf, 0x43, 0x75, 0xc7, 0xb9, 0x37,
        0x6e, 0x90, 0xe5, 0x3b, 0x81, 0xd4, 0xda, 0x68, 0xcd,
    ];
    let parsed_server_key_exchange = HandshakeMessageServerKeyExchange {
        identity_hint: vec![],
        elliptic_curve_type: EllipticCurveType::NamedCurve,
        named_curve: NamedCurve::X25519,
        public_key: raw_server_key_exchange[4..69].to_vec(),
        algorithm: SignatureHashAlgorithm {
            hash: HashAlgorithm::Sha1,
            signature: SignatureAlgorithm::Ecdsa,
        },

        signature: raw_server_key_exchange[73..144].to_vec(),
    };

    let mut reader = BufReader::new(raw_server_key_exchange.as_slice());
    let c = HandshakeMessageServerKeyExchange::unmarshal(&mut reader)?;
    assert_eq!(
        c, parsed_server_key_exchange,
        "handshakeMessageServerKeyExchange unmarshal: got {c:?}, want {parsed_server_key_exchange:?}"
    );

    let mut raw = vec![];
    {
        let mut writer = BufWriter::<&mut Vec<u8>>::new(raw.as_mut());
        c.marshal(&mut writer)?;
    }
    assert_eq!(
        raw, raw_server_key_exchange,
        "handshakeMessageServerKeyExchange marshal: got {raw:?}, want {raw_server_key_exchange:?}"
    );

    Ok(())
}
