///|
pub let ppid_dcep : UInt32 = 50U

///|
pub let ppid_string : UInt32 = 51U

///|
pub let ppid_binary : UInt32 = 53U

///|
#derive(Eq, Debug)
pub(all) enum ChannelType {
  Reliable
  ReliableUnordered
  PartialReliableRexmit
  PartialReliableRexmitUnordered
  PartialReliableTimed
  PartialReliableTimedUnordered
}

///|
#derive(Eq, Debug)
pub(all) struct OpenMessage {
  channel_type : ChannelType
  priority : Int32
  reliability_param : UInt32
  label : String
  protocol : String
}

///|
fn channel_type_byte(t : ChannelType) -> Byte {
  match t {
    Reliable => b'\x00'
    ReliableUnordered => b'\x80'
    PartialReliableRexmit => b'\x01'
    PartialReliableRexmitUnordered => b'\x81'
    PartialReliableTimed => b'\x02'
    PartialReliableTimedUnordered => b'\x82'
  }
}

///|
fn channel_type_from_byte(b : Byte) -> ChannelType {
  match b.to_int() {
    0x80 => ReliableUnordered
    0x01 => PartialReliableRexmit
    0x81 => PartialReliableRexmitUnordered
    0x02 => PartialReliableTimed
    0x82 => PartialReliableTimedUnordered
    _ => Reliable
  }
}

///|
pub fn OpenMessage::encode(self : OpenMessage) -> Bytes {
  let out : Array[Byte] = []
  out.push(b'\x03') // DATA_CHANNEL_OPEN
  out.push(channel_type_byte(self.channel_type))
  out.push(((self.priority >> 8) & 0xff).to_byte())
  out.push((self.priority & 0xff).to_byte())
  out.push(((self.reliability_param >> 24) & 0xffU).to_byte())
  out.push(((self.reliability_param >> 16) & 0xffU).to_byte())
  out.push(((self.reliability_param >> 8) & 0xffU).to_byte())
  out.push((self.reliability_param & 0xffU).to_byte())
  let lbytes = @utf8.encode(self.label)
  let pbytes = @utf8.encode(self.protocol)
  out.push(((lbytes.length() >> 8) & 0xff).to_byte())
  out.push((lbytes.length() & 0xff).to_byte())
  out.push(((pbytes.length() >> 8) & 0xff).to_byte())
  out.push((pbytes.length() & 0xff).to_byte())
  for b in lbytes {
    out.push(b)
  }
  for b in pbytes {
    out.push(b)
  }
  Bytes::from_array(out)
}

///|
pub fn OpenMessage::decode(raw : BytesView) -> OpenMessage? {
  if raw.length() < 12 || raw[0] != b'\x03' {
    return None
  }
  let channel_type = channel_type_from_byte(raw[1])
  let priority = (raw[2].to_int() << 8) | raw[3].to_int()
  let reliability_param = (raw[4].to_uint() << 24) |
    (raw[5].to_uint() << 16) |
    (raw[6].to_uint() << 8) |
    raw[7].to_uint()
  let llen = (raw[8].to_int() << 8) | raw[9].to_int()
  let plen = (raw[10].to_int() << 8) | raw[11].to_int()
  if 12 + llen + plen > raw.length() {
    return None
  }
  let label = @utf8.decode_lossy(raw[12:12 + llen])
  let protocol = @utf8.decode_lossy(raw[12 + llen:12 + llen + plen])
  Some({ channel_type, priority, reliability_param, label, protocol, })
}

///|
pub fn encode_ack() -> Bytes {
  b"\x02"
}

///|
pub fn is_ack(raw : BytesView) -> Bool {
  raw.length() >= 1 && raw[0] == b'\x02'
}

///|
#derive(Eq, Debug)
pub(all) struct DataChannel {
  id : Int32
  label : String
  protocol : String
  channel_type : ChannelType
  mut open : Bool
}

///|
#derive(Eq, Debug)
pub(all) struct ChannelEvent {
  channel_id : Int32
  text : String?
  binary : Bytes?
}

///|
pub struct Manager {
  assoc : @sctp.Association
  channels : Map[Int32, DataChannel]
  mut next_stream_id : Int32
}

///|
pub fn Manager::new(
  assoc : @sctp.Association,
  is_dtls_client : Bool,
) -> Manager {
  {
    assoc,
    channels: Map([]),
    next_stream_id: if is_dtls_client {
      0
    } else {
      1
    },
  }
}

///|
/// Open a new DataChannel and return `(channel, sctp_packet)`.
pub fn Manager::open_channel(
  self : Manager,
  label : String,
  protocol~ : String = "",
  channel_type~ : ChannelType = Reliable,
) -> (DataChannel, Bytes) {
  let id = self.next_stream_id
  self.next_stream_id += 2
  let dc : DataChannel = { id, label, protocol, channel_type, open: false, }
  self.channels[id] = dc
  let msg : OpenMessage = {
    channel_type,
    priority: 0,
    reliability_param: 0U,
    label,
    protocol,
  }
  (dc, self.assoc.send(id, ppid_dcep, msg.encode()))
}

///|
pub fn Manager::send_text(
  self : Manager,
  channel_id : Int32,
  text : String,
) -> Bytes {
  let unordered = match self.channels.get(channel_id) {
    Some(dc) =>
      dc.channel_type == ReliableUnordered ||
      dc.channel_type == PartialReliableRexmitUnordered ||
      dc.channel_type == PartialReliableTimedUnordered
    None => false
  }
  self.assoc.send(channel_id, ppid_string, @utf8.encode(text), unordered~)
}

///|
pub fn Manager::send_binary(
  self : Manager,
  channel_id : Int32,
  data : Bytes,
) -> Bytes {
  self.assoc.send(channel_id, ppid_binary, data)
}

///|
/// Process incoming SCTP data frames drained from `assoc`, returning
/// `(outbound_sctp_packets, received_channel_events)`.
pub fn Manager::poll_events(
  self : Manager,
) -> (Array[Bytes], Array[ChannelEvent]) {
  let out_pkts : Array[Bytes] = []
  let events : Array[ChannelEvent] = []
  for item in self.assoc.drain_received() {
    if item.ppid == ppid_dcep {
      if is_ack(item.payload) {
        match self.channels.get(item.stream_id) {
          Some(dc) => dc.open = true
          None => ()
        }
      } else {
        match OpenMessage::decode(item.payload) {
          Some(open_msg) => {
            self.channels[item.stream_id] = {
              id: item.stream_id,
              label: open_msg.label,
              protocol: open_msg.protocol,
              channel_type: open_msg.channel_type,
              open: true,
            }
            out_pkts.push(
              self.assoc.send(item.stream_id, ppid_dcep, encode_ack()),
            )
          }
          None => ()
        }
      }
    } else if item.ppid == ppid_string {
      events.push({
        channel_id: item.stream_id,
        text: Some(@utf8.decode_lossy(item.payload)),
        binary: None,
      })
    } else if item.ppid == ppid_binary {
      events.push({
        channel_id: item.stream_id,
        text: None,
        binary: Some(item.payload),
      })
    }
  }
  (out_pkts, events)
}