'use strict'
const UserChildUtils = use('App/Utils/UserChildUtils');
const connectedUsers = {

};

class UserChannelController {
  constructor({socket, request, auth}) {
    console.log(`User #${auth.user.id} connected`);
    this.socket = socket;
    this.request = request;
    this.user = auth.user;
    connectedUsers[this.user.id] = this;
    this.notifyOnConnection(true).catch(console.error);
    // socket.on('close', this.onClose.bind(this))
  }
  onClose() {
    this.notifyOnConnection(false)
        .then(_ => {
          delete connectedUsers[this.user.id];
        })
        .catch(console.error);
  }
  emit(event, data) {
    console.log(`sending ${event} to user #${this.user.id}`);
    this.socket.emit(event, data);
  }

  static getUserChannel(userId) {
    console.log(`user ${userId} has socket? ${!!connectedUsers[userId]}`)
    return connectedUsers[userId];
  }
  static isUserOnline(userId) {
    return !!UserChannelController.getUserChannel(userId);
  }
  async notifyOnConnection(online) {
    this.user.last_logged_in = new Date();
    try {
      await this.user.save();
    } catch (e) {
      console.error(e);
    }
    const userConnections =
        await UserChildUtils.getUserConnections(this.user.id);
    const notifiedIds = [];
    for (const child of userConnections.children) {
      for (const user of child.connections) {
        const channel = UserChannelController.getUserChannel(user.id);
        if (channel && notifiedIds.indexOf(user.id) < 0 &&
            user.id != this.user.id) {
          /// connection:online
          channel.emit(
              `connection:${online ? 'online' : 'offline'}`,
              this.user.toJSON());
          notifiedIds.push(user.id);
        }
      }
    }
    for (const child of userConnections.connections) {
      for (const user of child.connections) {
        const channel = UserChannelController.getUserChannel(user.id);
        if (channel && notifiedIds.indexOf(user.id) < 0 &&
            user.id != this.user.id) {
          channel.emit(
              `connection:${online ? 'online' : 'offline'}`,
              this.user.toJSON());
          notifiedIds.push(user.id);
        }
      }
    }
    return true;
  }
}

module.exports = UserChannelController
