/* eslint-disable @typescript-eslint/no-explicit-any */
import RTCIceTransport from './RTCIceTransport';
import RTCPeerConnection from './RTCPeerConnection';

export default class RTCDtlsTransport extends EventTarget implements globalThis.RTCDtlsTransport {
  #pc: RTCPeerConnection = null;
  #iceTransport = null;

  onstatechange: globalThis.RTCDtlsTransport['onstatechange'] = null;
  onerror: globalThis.RTCDtlsTransport['onstatechange'] = null;

  constructor(init: { pc: RTCPeerConnection }) {
    super();
    this.#pc = init.pc;

    this.#iceTransport = new RTCIceTransport({
      pc: init.pc,
    });

    // forward peerConnection events
    this.#pc.addEventListener('connectionstatechange', () => {
      const e = new Event('statechange');
      this.dispatchEvent(e);
      this.onstatechange?.(e);
    });
  }

  get iceTransport(): globalThis.RTCIceTransport {
    return this.#iceTransport;
  }

  get state(): globalThis.RTCDtlsTransportState {
    // reduce state from new, connecting, connected, disconnected, failed, closed, unknown
    // to RTCDtlsTRansport states new, connecting, connected, closed, failed
    let state = this.#pc ? this.#pc.connectionState : 'new';
    if (state === 'disconnected') {
      state = 'closed';
    }
    return state;
  }

  getRemoteCertificates(): ArrayBuffer[] {
    // TODO: implement
    return [new ArrayBuffer(0)];
  }
}
