// Copyright 2021-2022 Ian Jackson and contributors to Hippotat
// SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-Hippotat-OpenSSL-Exception
// There is NO WARRANTY.

use crate::prelude::*;

pub static SLIP_END_SLICE: &[u8] = &[SLIP_END];

#[derive(Error,Debug,Copy,Clone,Eq,PartialEq)]
pub enum PacketError {
  #[error("empty packet")]                 Empty,
  #[error("MTU exceeded ({len} > {mtu})")] MTU { len: usize, mtu: u32 },
  #[error("Invalid SLIP escape sequence")] SLIP,
  #[error("unexpected src addr {0:?}")]    Src(IpAddr),
  #[error("unexpected dst addr {0:?}")]    Dst(IpAddr),
  #[error("truncated, IPv{vsn}, len={len}")] Truncated { len: usize, vsn: u8 },
}

pub trait SlipMime: Copy { const CONV_TO: Option<bool>; }
#[derive(Copy,Clone,Debug)] pub struct Slip2Mime;
#[derive(Copy,Clone,Debug)] pub struct Mime2Slip;
#[derive(Copy,Clone,Debug)] pub struct SlipNoConv;
impl SlipMime for Slip2Mime { const CONV_TO: Option<bool> = Some(true); }
impl SlipMime for Mime2Slip { const CONV_TO: Option<bool> = Some(false); }
impl SlipMime for SlipNoConv { const CONV_TO: Option<bool> = None; }

#[derive(Debug,Error,Eq,PartialEq)]
pub enum SlipFramesError<E> where E: std::error::Error + 'static {
  #[error("only bad IP datagrams")] ErrorOnlyBad,
  #[error("{0}")] Other(#[from] E),
}
  
#[throws(SlipFramesError<EHE>)]
pub async fn processn<AC, EH, EHE, OUT, FOUT, ACR, M: SlipMime+Copy>(
  mime: M,
  mtu: u32,
  data: &[u8],
  addr_chk: AC,
  mut out: OUT,
  mut error_handler: EH
) where AC: Fn(&[u8]) -> Result<ACR, PacketError> + Copy + Send,
        OUT: FnMut((Box<[u8]>, ACR)) -> FOUT + Send,
        FOUT: Future<Output=Result<(), PacketError>> + Send,
        EH: FnMut(PacketError) -> Result<(), SlipFramesError<EHE>> + Send,
        EHE: std::error::Error + Send + 'static,
{
  //  eprintln!("before: {:?}", DumpHex(data));
  if data.is_empty() { return }
  let mut ok = false;
  let mut err = false;
  for packet in data.split(|&c| c == SLIP_END) {
    match async {
      let checked = process1(mime, mtu, packet, addr_chk);
      if matches!(checked, Err(PacketError::Empty)) { return Ok::<_,PE>(()) }
      out(checked?).await?;
      ok = true;
      Ok::<_,PE>(())
    }.await {
      Ok(()) => { },
      Err(e) => { err=true; error_handler(e)?; },
    }
  }
//  eprintln!(" after: {:?}", DumpHex(data));
  if err && !ok { throw!(SlipFramesError::ErrorOnlyBad) }
}

#[throws(PacketError)]
pub fn process1<AC, M: SlipMime, ACR>(
  _mime: M,
  mtu: u32,
  packet: &[u8],
  addr_chk: AC,
) -> (Box<[u8]>, ACR)
where AC: Fn(&[u8]) -> Result<ACR, PacketError>,
{
  if packet.len() == 0 {
    throw!(PacketError::Empty)
  }

  let mut packet: Box<[u8]> = packet.to_owned().into();
  let mut walk: &mut [u8] = &mut packet;
  let mut header = [0u8; HEADER_FOR_ADDR];
  let mut wheader = &mut header[..];
  let mut escapes = 0;

  while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
    |(i,&c)| match c {
      SLIP_ESC                               => Some((i,false)),
      SLIP_MIME_ESC if M::CONV_TO.is_some()  => Some((i,true)),
      _ => None,
    }
  ) {
    let _ = wheader.write(&walk[0..i]);
    if M::CONV_TO.is_some() {
      walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
    }
    if Some(was_mime) != M::CONV_TO {
      let c = match walk.get(i+1) {
        Some(&SLIP_ESC_ESC) => SLIP_ESC,
        Some(&SLIP_ESC_END) => SLIP_END,
        _ => throw!(PacketError::SLIP),
      };
      let _ = wheader.write(&[c]);
      walk = &mut walk[i+2 ..];
      escapes += 1;
    } else {
      let _ = wheader.write(&[SLIP_MIME_ESC]);
      walk = &mut walk[i+1 ..];
    }
  }
  let _ = wheader.write(walk);
  let wheader_len = wheader.len();
  let header = &header[0.. header.len() - wheader_len];

  let decoded_len = packet.len() - escapes;
  if decoded_len > mtu.sat() {
    throw!(PacketError::MTU { len: decoded_len, mtu });
  }

  let acr = addr_chk(header)?;

  (packet, acr)
}

pub type Frame = Vec<u8>;
pub type FramesData = Vec<Vec<u8>>;
// todo: https://github.com/tokio-rs/bytes/pull/504
//   pub type Frame = Box<[u8]>;
//   pub type FramesData = Vec<Frame>;
//       `From<Box<[u8]>>` is not implemented for `Bytes`
// when this is fixed, there are two `into`s in client.rs which 
// become redundant (search for todo:504)


#[derive(Default)]
pub struct Frames {
  frames: FramesData,
  total_len: usize,
  tried_full: bool,
}

impl Debug for Frames {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
  }
}

impl Frames {
  #[throws(Frame)]
  pub fn add(&mut self, max: u32, frame: Frame) {
    if frame.len() == 0 { return }
    let new_total = self.total_len + frame.len() + 1;
    if new_total > max.sat() { self.tried_full = true; throw!(frame); }
    self.total_len = new_total;
    self.frames.push(frame);
  }

  #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
  #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
}

impl From<Frames> for FramesData {
  fn from(frames: Frames) -> FramesData { frames.frames }
}

const HEADER_FOR_ADDR: usize = 40;

#[throws(PacketError)]
pub fn ip_packet_addr<const DST: bool>(header: &[u8]) -> IpAddr {
  let vsn = (header.get(0).ok_or_else(|| PE::Empty)? & 0xf0) >> 4;
  match vsn {
    4 if header.len() >= 20 => {
      let slice = &header[if DST { 16 } else { 12 }..][0..4];
      Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
    },

    6 if header.len() >= 40 => {
      let slice = &header[if DST { 24 } else { 8 }..][0..16];
      Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
    },

    _ => throw!(PE::Truncated{ vsn, len: header.len() }),
  }
}

#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
pub struct DumpHex<'b>(pub &'b [u8]);
impl Debug for DumpHex<'_> {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    for v in self.0 { write!(f, "{:02x}", v)?; }
    match str::from_utf8(self.0) {
      Ok(s) => write!(f, "={:?}", s)?,
      Err(x) => write!(f, "={:?}..",
                       str::from_utf8(&self.0[0..x.valid_up_to()]).unwrap()
      )?,
    }
  }
}

#[tokio::test]
async fn mime_slip_to_mime() {
  use PacketError as PE;
  const MTU: u32 = 10;

  async fn chk<M:SlipMime>(m: M, i: &[u8],
                           exp_p: &[&[u8]],
                           exp_e: &[PacketError],
                           exp_r: Result<(),SlipFramesError<Void>>)
  {
    dbg!(M::CONV_TO, DumpHex(i));
    let mut got_e = vec![];
    let mut got_p = vec![];
    let got_r = processn(
      m, MTU, i,
      |_|Ok(()),
      |(p,())| { got_p.push(p); async { Ok(()) } },
      |e| Ok::<_,SlipFramesError<Void>>(got_e.push(e))
    ).await;
    assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
                exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
    assert_eq!( got_e,
                exp_e );
    assert_eq!( got_r,
                exp_r );
  }
  use SlipFramesError::ErrorOnlyBad;

  chk(Slip2Mime,
       &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
    &[           &[ b'-',     SLIP_ESC_END, SLIP_ESC, b'X' ] ],
    &[ ],
      Ok(())).await;

  chk(Slip2Mime,
       &[ SLIP_END, SLIP_ESC, b'y' ], &[],
    &[ PE::SLIP ],
      Err(ErrorOnlyBad)).await;

  chk(Slip2Mime,
       &[ SLIP_END, b'-',     b'y' ],
    &[           &[ SLIP_ESC, b'y' ] ],
    &[ ],
      Ok(())).await;

  chk(Slip2Mime,
       &[b'x'; 20],
    &[             ],
    &[ PE::MTU { len: 20, mtu: MTU } ],
      Err(ErrorOnlyBad)).await;

  chk(SlipNoConv,
       &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
    &[           &[ SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ] ],
    &[ ],
      Ok(())).await;
}


