use crate::{Error, payload::{Decode, Encode}, Payload};
use std::io::{Read, Seek, SeekFrom};
use crate::payload::{SeStringChunkKind, SeInteractableKind};

#[derive(Debug, Clone, PartialEq)]
pub struct MapLinkPayload {
    pub territory_type: u32,
    pub map: u32,
    pub raw_x: i32,
    pub raw_y: i32,
}

impl Decode for MapLinkPayload {
    fn decode<R: Read + Seek>(mut reader: R, _chunk_len: usize) -> Result<Self, Error> {
        let (territory_type, map) = Self::read_packed_integers(&mut reader)?;
        let raw_x = Self::read_integer(&mut reader)? as i32;
        let raw_y = Self::read_integer(&mut reader)? as i32;

        reader.seek(SeekFrom::Current(2)).map_err(Error::from)?;

        Ok(Self {
            territory_type,
            map,
            raw_x,
            raw_y,
        })
    }
}

impl Encode for MapLinkPayload {
    fn encode(&self) -> Vec<u8> {
        use std::iter::once;

        let territory_map_packed = Self::make_packed_integers(self.territory_type, self.map);
        let x = Self::make_integer(self.raw_x as u32);
        let y = Self::make_integer(self.raw_y as u32);
        let chunk_len = 4 + territory_map_packed.len() + x.len() + y.len();

        once(Payload::START_BYTE)
            .chain(once(SeStringChunkKind::Interactable.as_u8()))
            .chain(once(chunk_len as u8))
            .chain(once(SeInteractableKind::MapPositionLink.as_u8()))
            .chain(territory_map_packed.into_iter())
            .chain(x.into_iter())
            .chain(y.into_iter())
            .chain(once(0xFF))
            .chain(once(0x01))
            .chain(once(Payload::END_BYTE))
            .collect()
    }
}
