///|
#derive(Eq, Debug)
pub(all) enum PeerRole {
  Offerer
  Answerer
}

///|
#derive(Eq, Debug)
pub(all) enum PeerState {
  New
  Connecting
  Connected
  Closed
}

///|
#derive(Eq, Debug)
pub(all) enum IncomingEvent {
  StunPacket
  RtpPacket(@rtp.Packet)
  RtcpPacket(@rtp.RtcpPacket)
  DataChannelEvent(@dc.ChannelEvent)
  DtlsPacket(Bytes)
  UnknownPacket
}

///|
/// High-level WebRTC Peer orchestrating SDP, ICE, SRTP, SCTP, and DataChannels.
pub struct Peer {
  role : PeerRole
  ice : @ice.Agent
  local_fingerprint : @sdp.Fingerprint
  sctp : @sctp.Association
  dc : @dc.Manager
  mut srtp_tx : @srtp.Context?
  mut srtp_rx : @srtp.Context?
  mut state : PeerState
}

///|
pub fn Peer::new(
  role : PeerRole,
  ice_creds : @sdp.IceCreds,
  local_addr : @moonip.AddrPort,
  fingerprint : @sdp.Fingerprint,
) -> Peer {
  let ice_role = match role {
    Offerer => @ice.Controlling
    Answerer => @ice.Controlled
  }
  let ice = @ice.Agent::new(ice_role, ice_creds)
  ice.add_local_candidate({
    foundation: "1",
    component: 1,
    addr: local_addr,
    typ: @ice.Host,
    priority: @ice.candidate_priority(@ice.Host),
  })
  let sctp = @sctp.Association::new()
  let dc = @dc.Manager::new(sctp, role == Offerer)
  {
    role,
    ice,
    local_fingerprint: fingerprint,
    sctp,
    dc,
    srtp_tx: None,
    srtp_rx: None,
    state: New,
  }
}

///|
pub fn Peer::create_sdp(self : Peer) -> @sdp.SessionDesc {
  let setup = match self.role {
    Offerer => @sdp.Actpass
    Answerer => @sdp.Passive
  }
  let cands : Array[@sdp.CandidateLine] = []
  for c in self.ice.local_candidates {
    cands.push(c.to_sdp())
  }
  @sdp.data_channel_sdp(
    self.ice.local_creds,
    self.local_fingerprint,
    setup,
    candidates=cands,
  )
}

///|
pub fn Peer::set_remote_sdp(self : Peer, desc : @sdp.SessionDesc) -> Unit {
  match desc.ice {
    Some(creds) => self.ice.set_remote_creds(creds)
    None =>
      if desc.media.length() > 0 {
        match desc.media[0].ice {
          Some(creds) => self.ice.set_remote_creds(creds)
          None => ()
        }
      }
  }
  for m in desc.media {
    for c in m.candidates {
      match @ice.Candidate::from_sdp(c) {
        Some(cand) => self.ice.add_remote_candidate(cand)
        None => ()
      }
    }
  }
  if self.state == New {
    self.state = Connecting
  }
}

///|
pub fn Peer::set_srtp_keys(
  self : Peer,
  profile : @moontls_srtp.Profile,
  tx_key : BytesView,
  tx_salt : BytesView,
  rx_key : BytesView,
  rx_salt : BytesView,
) -> Unit raise @srtp.SrtpError {
  self.srtp_tx = Some(@srtp.Context::new(profile, tx_key, tx_salt))
  self.srtp_rx = Some(@srtp.Context::new(profile, rx_key, rx_salt))
}

///|
pub fn Peer::build_ice_check(
  self : Peer,
  tx_id : Bytes,
  nominate~ : Bool = true,
) -> Bytes? {
  self.ice.build_check(0, tx_id, nominate~)
}

///|
pub fn Peer::initiate_sctp(self : Peer) -> Bytes {
  self.sctp.initiate()
}

///|
pub fn Peer::open_channel(
  self : Peer,
  label : String,
) -> (@dc.DataChannel, Bytes) {
  self.dc.open_channel(label)
}

///|
pub fn Peer::send_text(self : Peer, channel_id : Int32, text : String) -> Bytes {
  self.dc.send_text(channel_id, text)
}

///|
pub fn Peer::send_rtp(
  self : Peer,
  pkt : @rtp.Packet,
) -> Bytes raise @srtp.SrtpError {
  let raw = pkt.encode()
  match self.srtp_tx {
    Some(ctx) => ctx.protect_rtp(raw)
    None => raw
  }
}

///|
/// Handle an incoming transport datagram (demultiplexed by RFC 7983) and
/// return `(outbound_packets, events)`.
pub fn Peer::receive(
  self : Peer,
  packet : BytesView,
  from : @moonip.AddrPort,
) -> (Array[Bytes], Array[IncomingEvent]) {
  let out : Array[Bytes] = []
  let events : Array[IncomingEvent] = []
  match @demux.classify(packet) {
    @demux.Stun => {
      match self.ice.handle_stun(packet, from) {
        Some(reply) => out.push(reply)
        None => ()
      }
      if self.ice.state == @ice.Completed || self.ice.state == @ice.Connected {
        self.state = Connected
      }
      events.push(StunPacket)
    }
    @demux.RtpRtcp =>
      if @demux.is_rtcp(packet) {
        let plain = match self.srtp_rx {
          Some(ctx) =>
            try ctx.unprotect_rtcp(packet) catch {
              _ => return (out, events)
            } noraise {
              p => p
            }
          None => packet.to_owned()
        }
        try @rtp.RtcpPacket::decode(plain) catch {
          _ => ()
        } noraise {
          r => events.push(RtcpPacket(r))
        }
      } else {
        let plain = match self.srtp_rx {
          Some(ctx) =>
            try ctx.unprotect_rtp(packet) catch {
              _ => return (out, events)
            } noraise {
              p => p
            }
          None => packet.to_owned()
        }
        try @rtp.Packet::decode(plain) catch {
          _ => ()
        } noraise {
          r => events.push(RtpPacket(r))
        }
      }
    @demux.Dtls => events.push(DtlsPacket(packet.to_owned()))
    _ => events.push(UnknownPacket)
  }
  (out, events)
}

///|
/// Handle an incoming decrypted SCTP packet (after DTLS decryption) and return
/// `(outbound_sctp_packets, datachannel_events)`.
pub fn Peer::receive_sctp(
  self : Peer,
  packet : BytesView,
) -> (Array[Bytes], Array[@dc.ChannelEvent]) raise @sctp.SctpError {
  let out = self.sctp.handle_packet(packet)
  let (dc_out, evs) = self.dc.poll_events()
  for p in dc_out {
    out.push(p)
  }
  (out, evs)
}