import { RdDBaseActor } from "./actor/base-actor.js";
import { SYSTEM_SOCKET_ID } from "./constants.js";
import { Misc } from "./misc.js";

export class Remote {

  static onSocketMessage(sockmsg) {
    switch (sockmsg.msg) {
      case "msg_remote_call":
        return Remote.onRemoteCall(sockmsg.userId, sockmsg.data);
    }
  }

  static remoteCall({ userId = undefined, documentName, documentId, tokenId = undefined, method, args }) {
    const callData = { documentName, documentId, tokenId, method, args }
    const sendToUserId = Misc.connectedUserOrGM(userId)
    if (sendToUserId == undefined) {
      ui.notifications.error(`Impossible d'envoyer un message à ${userId}`)
    }
    else if (sendToUserId == game.user.id) {
      Remote.onRemoteCall(game.user.id, callData)
      return false
    }
    else {
      game.socket.emit(SYSTEM_SOCKET_ID, { msg: "msg_remote_call", userId: sendToUserId, data: callData })
      return true
    }
  }

  static onRemoteCall(userId, callData) {
    if (userId == game.user.id) {
      // Seul le joueur choisi effectue l'appel: le joueur courant si propriétaire de l'actor, ou le MJ sinon
      const doc = Remote.getDoc(callData)
      if (doc) {
        const args = callData.args;
        const method = callData.method;
        console.info(`Remote.onRemoteCall: ${callData.documentName} ${callData.documentId}, appel de ${method}(`, ...args, ')')
        doc[method](...args)
      }
    }
  }

  static getDoc(callData) {
    switch (callData.documentName) {
      case 'Actor': return RdDBaseActor.getRealActor(callData.documentId, callData.tokenId)
      case 'Item': return game.items.get(callData.documentId)
      case 'RollTable': return game.tables.get(callData.documentId)
      case 'ChatMessage': return game.messages.get(callData.documentId)
    }
    return undefined
  }

}