///|
#derive(Eq, Debug)
pub(all) enum CandidateType {
  Host
  Srflx
  Prflx
  Relay
}

///|
pub impl Show for CandidateType with fn output(self, logger) {
  match self {
    Host => logger.write_string("host")
    Srflx => logger.write_string("srflx")
    Prflx => logger.write_string("prflx")
    Relay => logger.write_string("relay")
  }
}

///|
#derive(Eq, Debug)
pub(all) enum Role {
  Controlling
  Controlled
}

///|
#derive(Eq, Debug)
pub(all) enum PairState {
  Waiting
  InProgress
  Succeeded
  Failed
}

///|
#derive(Eq, Debug)
pub(all) enum IceState {
  New
  Checking
  Connected
  Completed
  Failed
}

///|
#derive(Eq, Debug)
pub(all) struct Candidate {
  foundation : String
  component : Int32
  addr : @moonip.AddrPort
  typ : CandidateType
  priority : UInt32
}

///|
#derive(Eq, Debug)
pub(all) struct CandidatePair {
  local_cand : Candidate
  remote_cand : Candidate
  priority : UInt64
  mut state : PairState
  mut nominated : Bool
}

///|
/// RFC 8445 §5.1.2.1 candidate priority calculation.
pub fn candidate_priority(
  typ : CandidateType,
  local_pref~ : UInt32 = 65535U,
  component~ : Int32 = 1,
) -> UInt32 {
  let type_pref : UInt32 = match typ {
    Host => 126U
    Prflx => 110U
    Srflx => 100U
    Relay => 0U
  }
  (type_pref << 24) +
  (local_pref << 8) +
  (256U - component.reinterpret_as_uint())
}

///|
/// RFC 8445 §6.1.2.3 candidate pair priority calculation.
pub fn pair_priority(
  controlling_prio : UInt32,
  controlled_prio : UInt32,
) -> UInt64 {
  let g = if controlling_prio > controlled_prio {
    controlling_prio.to_uint64()
  } else {
    controlled_prio.to_uint64()
  }
  let d = if controlling_prio < controlled_prio {
    controlling_prio.to_uint64()
  } else {
    controlled_prio.to_uint64()
  }
  let bonus : UInt64 = if controlling_prio > controlled_prio {
    1UL
  } else {
    0UL
  }
  (1UL << 32) * d + 2UL * g + bonus
}

///|
pub fn Candidate::to_sdp(self : Candidate) -> @sdp.CandidateLine {
  {
    foundation: self.foundation,
    component: self.component,
    transport: "udp",
    priority: self.priority,
    address: self.addr.addr().to_string(),
    port: self.addr.port(),
    typ: "\{self.typ}",
  }
}

///|
pub fn Candidate::from_sdp(line : @sdp.CandidateLine) -> Candidate? {
  let addr = try @moonip.Addr::parse(line.address) catch {
    _ => return None
  } noraise {
    a => a
  }
  let ap = try @moonip.AddrPort::new(addr, line.port) catch {
    _ => return None
  } noraise {
    p => p
  }
  let typ = match line.typ {
    "host" => Host
    "srflx" => Srflx
    "prflx" => Prflx
    "relay" => Relay
    _ => Host
  }
  Some({
    foundation: line.foundation,
    component: line.component,
    addr: ap,
    typ,
    priority: line.priority,
  })
}

///|
pub struct Agent {
  role : Role
  local_creds : @sdp.IceCreds
  mut remote_creds : @sdp.IceCreds?
  tie_breaker : UInt64
  local_candidates : Array[Candidate]
  remote_candidates : Array[Candidate]
  pairs : Array[CandidatePair]
  mut state : IceState
}

///|
pub fn Agent::new(
  role : Role,
  local_creds : @sdp.IceCreds,
  tie_breaker~ : UInt64 = 1UL,
) -> Agent {
  {
    role,
    local_creds,
    remote_creds: None,
    tie_breaker,
    local_candidates: [],
    remote_candidates: [],
    pairs: [],
    state: New,
  }
}

///|
pub fn Agent::add_local_candidate(self : Agent, cand : Candidate) -> Unit {
  self.local_candidates.push(cand)
}

///|
pub fn Agent::set_remote_creds(self : Agent, creds : @sdp.IceCreds) -> Unit {
  self.remote_creds = Some(creds)
}

///|
pub fn Agent::add_remote_candidate(self : Agent, cand : Candidate) -> Unit {
  self.remote_candidates.push(cand)
  for lc in self.local_candidates {
    if lc.component == cand.component {
      let (ctrl, ctrld) = match self.role {
        Controlling => (lc.priority, cand.priority)
        Controlled => (cand.priority, lc.priority)
      }
      self.pairs.push({
        local_cand: lc,
        remote_cand: cand,
        priority: pair_priority(ctrl, ctrld),
        state: Waiting,
        nominated: false,
      })
    }
  }
  if self.pairs.length() > 0 && self.state == New {
    self.state = Checking
  }
}

///|
/// Build a STUN Binding Request for connectivity checking on pair `idx`.
pub fn Agent::build_check(
  self : Agent,
  idx : Int32,
  tx_id : Bytes,
  nominate~ : Bool = false,
) -> Bytes? {
  if idx < 0 || idx >= self.pairs.length() {
    return None
  }
  let rc = match self.remote_creds {
    Some(c) => c
    None => return None
  }
  let pair = self.pairs[idx]
  pair.state = InProgress
  let attrs : Array[@stun.Attr] = [
    @stun.Username(rc.ufrag + ":" + self.local_creds.ufrag),
    @stun.Priority(pair.local_cand.priority),
  ]
  match self.role {
    Controlling => {
      attrs.push(@stun.IceControlling(self.tie_breaker))
      if nominate {
        attrs.push(@stun.UseCandidate)
      }
    }
    Controlled => attrs.push(@stun.IceControlled(self.tie_breaker))
  }
  let msg : @stun.Message = {
    class: @stun.Request,
    method_: @stun.Binding,
    tx_id,
    attrs,
  }
  Some(
    @stun.encode(msg, integrity_key=@utf8.encode(rc.pwd), with_fingerprint=true),
  )
}

///|
/// Handle an incoming STUN connectivity check packet from `from`.
/// Returns an encoded STUN Binding SuccessResponse if the packet was a valid Request.
pub fn Agent::handle_stun(
  self : Agent,
  packet : BytesView,
  from : @moonip.AddrPort,
) -> Bytes? {
  let msg = try @stun.decode(packet) catch {
    _ => return None
  } noraise {
    m => m
  }
  match msg.class {
    @stun.Request => {
      if !@stun.verify_integrity(packet, @utf8.encode(self.local_creds.pwd)) {
        return None
      }
      let mut use_cand = false
      for attr in msg.attrs {
        if attr == @stun.UseCandidate {
          use_cand = true
        }
      }
      for pair in self.pairs {
        if pair.remote_cand.addr == from {
          pair.state = Succeeded
          if use_cand || self.role == Controlled {
            pair.nominated = use_cand
          }
          self.state = if use_cand { Completed } else { Connected }
        }
      }
      let resp : @stun.Message = {
        class: @stun.SuccessResponse,
        method_: @stun.Binding,
        tx_id: msg.tx_id,
        attrs: [@stun.XorMappedAddress(from)],
      }
      Some(
        @stun.encode(
          resp,
          integrity_key=@utf8.encode(self.local_creds.pwd),
          with_fingerprint=true,
        ),
      )
    }
    @stun.SuccessResponse => {
      for pair in self.pairs {
        if pair.remote_cand.addr == from {
          pair.state = Succeeded
          if self.role == Controlling {
            pair.nominated = true
            self.state = Completed
          } else {
            self.state = Connected
          }
        }
      }
      None
    }
    _ => None
  }
}

///|
pub fn Agent::selected_pair(self : Agent) -> CandidatePair? {
  for pair in self.pairs {
    if pair.nominated && pair.state == Succeeded {
      return Some(pair)
    }
  }
  for pair in self.pairs {
    if pair.state == Succeeded {
      return Some(pair)
    }
  }
  None
}