'use strict'
const User = use('App/Models/User');
const UserChildUtils = use('App/Utils/UserChildUtils');
const Child = use('App/Models/Child');
const IceServer = use('App/Models/IceServer');
const UserChannel = use('App/Controllers/Ws/UserChannelController')
const calls = {};

class SignalingController {
  constructor({socket, request, auth, call}) {
    this.callId = socket.topic.split(':')[1];
    this.user = auth.user;
    this.socket = socket;
    this.request = request;
    this.register(call)
        .then(_ => {
          console.log(`User #${this.user.id} connected to call ${this.callId}`);
        })
        .catch(e => {
          console.error(e);
        });
  }
  async register(callModel) {
    if (!calls[this.callId])
      calls[this.callId] =
          new CallSession(callModel, this.onCallEnded.bind(this));
    else
      console.log(`Call #${this.callId} Already Found`);
    const callSession = calls[this.callId];
    const success = await callSession.registerUser(this.user, this.socket)
    if (!success) throw new Error('Invalid User');
    return true;
  }
  onCallEnded(callId) {
    console.log(`Call ${callId} Ended`);
    delete calls[callId];
  }
  onClose() {
    calls[this.callId].removeUser(this.user);
    console.log(`User #${this.user.id} left call ${this.callId}`);
  }
}

class CallSession {
  // states: NEW -> STARTED -> IN_PROGRESS -> ENDED
  constructor(callModel, onCallEndedCallback) {
    this.onCallEndedCallback = onCallEndedCallback;
    this.callId = callModel.id;
    this.callModel = callModel;
    this.hostId = 2;
    this.state = callModel.state;
    this.user_1 = {id: callModel.user_1, socket: null, userModel: null};
    this.user_2 = {id: callModel.user_2, socket: null, userModel: null};
    this.startTime = Date.now();
    this.heartbeat =
        setInterval(this.onHeartbeat.bind(this), 1000);  // Every second
  }
  onHeartbeat() {
    const now = Date.now();
    const elapsed = ((now - this.startTime) / 60000).toPrecision(1);
    const newStateTimeout = 5;       // 5 min
    const startedStateTimeout = 10;  // 10 min
    // console.log(`Heartbeat for call #${this.callId} State: ${
    //     this.state}, time-elapsed: ${(elapsed)}min`);
    if (this.state === 'ENDED') return this.endCall();
    if (this.state === 'NEW' && elapsed >= newStateTimeout)
      return this.endCall();
    if (this.state === 'STARTED' && elapsed >= startedStateTimeout)
      return this.endCall();
  }
  removeUser(user) {
    let userIndex = -1;
    if (this.user_1.id === user.id)
      userIndex = 1;
    else if (this.user_2.id === user.id)
      userIndex = 2;
    if (userIndex < 0) return false;
    this[`user_${userIndex}`].userModel = null;
    this[`user_${userIndex}`].socket = null;
    this.updateState();
    if (this.state === 'ENDED') this.endCall();
  }
  async registerUser(user, socket) {
    if (!this.child) this.child = await Child.find(this.callModel.child_id);
    let userIndex = -1;
    if (this.user_1.id === user.id)
      userIndex = 1;
    else if (this.user_2.id === user.id)
      userIndex = 2;
    if (userIndex < 0) return false;
    const otherUser = userIndex === 1 ? 2 : 1;
    this[`user_${userIndex}`].userModel = user;
    this[`user_${userIndex}`].socket = socket;
    socket.on('wrtc:sdp:offer', this.onSdpOffer.bind(this));
    socket.on('wrtc:sdp:answer', this.onSdpAnswer.bind(this));
    socket.on('wrtc:ice', this.onIceCandidate.bind(this));
    socket.on('call:host:changed', this.onHostChanged.bind(this));
    socket
        .on('book:action:flip-page', this.onActionBookFlip.bind(this))
            await this.updateState();
    if (this.state === 'STARTED') {
      await this.sendStandby(socket, userIndex);
      // Send event to other user about the call
      console.log(
          `trying to find user ${this[`user_${otherUser}`].id} channel...`);
      const otherUserChannel =
          UserChannel.getUserChannel(this[`user_${otherUser}`].id);
      if (otherUserChannel) {
        // console.log(otherUserChannel);
        console.log('Sending notification to other user');
        const payload = {callId: this.callId, child: this.child.toJSON()};
        console.dir(payload);
        otherUserChannel.emit('call:incoming', payload);
      }
    } else if (this.state === 'IN_PROGRESS')
      await this.sendStart(socket, userIndex);
    return true;
  }
  endCall() {
    this.state = 'ENDED';
    if (this.callModel.state != 'ENDED') {
      this.callModel.state = this.state;
      this.callModel.save();
    }
    if (this.user_1.socket) this.user_1.socket.close();
    if (this.user_2.socket) this.user_2.socket.close();
    clearInterval(this.heartbeat);
    this.onCallEndedCallback(this.callId);
  }

  async sendStandby(socket, userIndex) {
    console.log(`Call #${this.callId} sendStandby -> ${userIndex}`);
    const iceServers = (await IceServer.all()).rows.map(i => i.toJSON());
    socket.emit('call:standby', {
      iceServers,
      id: userIndex,
      child: this.child.toJSON(),
      users: await this.callModel.getUsers(),
      hostId: this.hostId
    });
  }
  async sendStart(socket, userIndex) {
    console.log(`Call #${this.callId} sendStart -> ${userIndex}`);
    const iceServers = (await IceServer.all()).rows.map(i => i.toJSON());
    socket.emit('call:start', {
      iceServers,
      id: userIndex,
      child: this.child.toJSON(),
      users: await this.callModel.getUsers(),
      hostId: this.hostId
    });
  }
  async updateState() {
    console.log(`Call #${this.callId} state=${this.state}`);
    switch (this.state) {
      case 'NEW':
        if (this.areAllPartnersConnected())
          this.state = 'IN_PROGRESS';
        else
          this.state = 'STARTED';
        break;
      case 'STARTED':
        if (this.areAllPartnersConnected()) this.state = 'IN_PROGRESS';
        break;
      case 'IN_PROGRESS':
        if (!this.areAllPartnersConnected()) this.state = 'ENDED';
        break;
    }
    this.callModel.state = this.state;
    await this.callModel.save();
    console.log(`Call #${this.callId} state=${this.state}`);
  }
  areAllPartnersConnected() {
    return !!this.user_1.socket && !!this.user_2.socket;
  }
  async onIceCandidate(payload) {
    const {from = payload.id, ice} = payload;
    const to = from === 1 ? 2 : 1;
    this[`user_${to}`].socket.emit('wrtc:ice', {ice});
    console.log(`[Signal] [onIceCandidate] ${from} -> ${to}`);
    return true;
  }
  async onSdpOffer(payload) {
    const {from = payload.id, sdp} = payload;
    const to = from === 1 ? 2 : 1;
    this[`user_${to}`].socket.emit('wrtc:sdp:offer', {sdp});
    console.log(`[Signal] [onSdpOffer] ${from} -> ${to}`);
    return true;
  }

  async onSdpAnswer(payload) {
    const {from = payload.id, sdp} = payload;
    const to = from === 1 ? 2 : 1;
    this[`user_${to}`].socket.emit('wrtc:sdp:answer', {sdp});
    console.log(`[Signal] [onSdpAnswer] ${from} -> ${to}`);
    return true;
  }

  onActionBookFlip(payload) {
    const {from = payload.id, direction} = payload;
    const to = from === 1 ? 2 : 1;
    this[`user_${to}`].socket.emit('book:action:flip-page', {direction});
    console.log(
        `[Signal] [book] [action] [flip] [${direction}] ${from} -> ${to}`);
    return true;
  }
  async onHostChanged(payload) {
    const {from = payload.id, hostId} = payload;
    const to = from === 1 ? 2 : 1;
    this.hostId = hostId;
    this[`user_${to}`].socket.emit('call:host:changed', {hostId});
    console.log(
        `[Signal] [host] [changed] [hostId=${hostId}] ${from} -> ${to}`);
    return true;
  }
}

module.exports = SignalingController
