import { ChatEvent } from '../../../shared-kernel';
import {
  P2P_TYPE_SCREEN_SHARE_REQUEST,
  P2P_TYPE_SCREEN_SHARE_STOP,
  P2P_TYPE_SCREEN_STATE
} from '../realtime.constants';

interface RemoteScreenShareRequestControllerDependencies {
  getConnectedPeerIds(): string[];
  sendToPeer(peerId: string, event: ChatEvent): void;
  clearRemoteScreenShareStream(peerId: string): void;
  requestScreenShareForPeer(peerId: string): void;
  stopScreenShareForPeer(peerId: string): void;
  clearScreenShareRequest(peerId: string): void;
}

export class RemoteScreenShareRequestController {
  private remoteScreenShareRequestsEnabled = false;
  private readonly desiredRemoteScreenSharePeers = new Set<string>();
  private readonly activeRemoteScreenSharePeers = new Set<string>();

  constructor(
    private readonly dependencies: RemoteScreenShareRequestControllerDependencies
  ) {}

  handlePeerConnected(peerId: string): void {
    if (this.remoteScreenShareRequestsEnabled && this.desiredRemoteScreenSharePeers.has(peerId)) {
      this.requestRemoteScreenShares([peerId]);
    }
  }

  handlePeerDisconnected(peerId: string): void {
    this.activeRemoteScreenSharePeers.delete(peerId);
    this.dependencies.clearScreenShareRequest(peerId);
  }

  handlePeerControlMessage(event: ChatEvent): void {
    if (!event.fromPeerId) {
      return;
    }

    if (event.type === P2P_TYPE_SCREEN_STATE && event.isScreenSharing === false) {
      this.dependencies.clearRemoteScreenShareStream(event.fromPeerId);
      return;
    }

    if (event.type === P2P_TYPE_SCREEN_SHARE_REQUEST) {
      this.dependencies.requestScreenShareForPeer(event.fromPeerId);
      return;
    }

    if (event.type === P2P_TYPE_SCREEN_SHARE_STOP) {
      this.dependencies.stopScreenShareForPeer(event.fromPeerId);
    }
  }

  syncRemoteScreenShareRequests(peerIds: string[], enabled: boolean): void {
    const nextDesiredPeers = new Set(
      peerIds.filter((peerId): peerId is string => !!peerId)
    );

    if (!enabled) {
      this.remoteScreenShareRequestsEnabled = false;
      this.desiredRemoteScreenSharePeers.clear();
      this.stopRemoteScreenShares([...this.activeRemoteScreenSharePeers]);
      return;
    }

    this.remoteScreenShareRequestsEnabled = true;

    for (const activePeerId of [...this.activeRemoteScreenSharePeers]) {
      if (!nextDesiredPeers.has(activePeerId)) {
        this.stopRemoteScreenShares([activePeerId]);
      }
    }

    this.desiredRemoteScreenSharePeers.clear();
    nextDesiredPeers.forEach((peerId) => this.desiredRemoteScreenSharePeers.add(peerId));
    this.requestRemoteScreenShares([...nextDesiredPeers]);
  }

  clear(): void {
    this.remoteScreenShareRequestsEnabled = false;
    this.desiredRemoteScreenSharePeers.clear();
    this.activeRemoteScreenSharePeers.clear();
  }

  private requestRemoteScreenShares(peerIds: string[]): void {
    const connectedPeerIds = new Set(this.dependencies.getConnectedPeerIds());

    for (const peerId of peerIds) {
      if (!connectedPeerIds.has(peerId) || this.activeRemoteScreenSharePeers.has(peerId)) {
        continue;
      }

      this.dependencies.sendToPeer(peerId, { type: P2P_TYPE_SCREEN_SHARE_REQUEST });
      this.activeRemoteScreenSharePeers.add(peerId);
    }
  }

  private stopRemoteScreenShares(peerIds: string[]): void {
    const connectedPeerIds = new Set(this.dependencies.getConnectedPeerIds());

    for (const peerId of peerIds) {
      if (this.activeRemoteScreenSharePeers.has(peerId) && connectedPeerIds.has(peerId)) {
        this.dependencies.sendToPeer(peerId, { type: P2P_TYPE_SCREEN_SHARE_STOP });
      }

      this.activeRemoteScreenSharePeers.delete(peerId);
      this.dependencies.clearRemoteScreenShareStream(peerId);
    }
  }
}
