use crate::{Error, payload::{Decode, Encode}, Payload};
use std::{
    io::{Read, Seek},
    iter::once,
};
use byteorder::ReadBytesExt;
use crate::payload::SeStringChunkKind;

#[derive(Debug, Clone, PartialEq)]
pub struct AutoTranslatePayload {
    pub group: u8,
    pub key: u32,
}

impl Decode for AutoTranslatePayload {
    fn decode<R: Read + Seek>(mut reader: R, _chunk_len: usize) -> Result<Self, Error> {
        let group = reader.read_u8().map_err(Error::from)?;
        let key = Self::read_integer(reader)?;
        Ok(Self {
            group,
            key,
        })
    }
}

impl Encode for AutoTranslatePayload {
    fn encode(&self) -> Vec<u8> {
        let key = Self::make_integer(self.key);
        let chunk_len = key.len() + 2;

        once(Payload::START_BYTE)
            .chain(once(SeStringChunkKind::AutoTranslate.as_u8()))
            .chain(once(chunk_len as u8))
            .chain(once(self.group))
            .chain(key.into_iter())
            .chain(once(Payload::END_BYTE))
            .collect()
    }
}
