import { DialogSplitItem } from "./dialog-split-item.js";
import { RdDItem } from "./item.js";

export class RdDSheetUtility {

  static getOptions(document, editable) {
    const userRightLevel = game.user.isGM
      ? CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER
      : document.getUserLevel(game.user);
    return {
      isGM: game.user.isGM,
      isOwned: document.parent ? true : false,
      editable: editable,
      cssClass: editable ? "editable" : "locked",
      isLimited: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,
      isObserver: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,
      isOwner: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER
    }
  }

  static mergeDocumentRights(options, document, editable) {
    const newOptions = RdDSheetUtility.getOptions(document, editable);
    foundry.utils.mergeObject(options, newOptions);
    return options;
  }


  static getItem(event, actor) {
    return actor.items.get(RdDSheetUtility.getItemId(event))
  }

  static getItemId(event) {
    return RdDSheetUtility.getEventItemData(event, "item-id");
  }

  static getEventItemData(event, property) {
    const node = RdDSheetUtility.getEventElement(event);
    return node?.data(property);
  }

  static getEventElement(event) {
    return $(event.currentTarget)?.parents(".item");
  }

  static async prepareItemDropParameters(destItemId, actor, dragData, objetVersConteneur) {
    let item = fromUuidSync(dragData.uuid);
    if (item.pack && !item.system) {
      item = await RdDItem.getCorrespondingItem(item);
    }
    if (actor.canReceive(item)) {
      if (!actor.prototypeToken.actorLink && actor.token) {
        ui.notifications.warn(`Impossible de donner ${item.name} à ${actor.name}, c'est un acteur temporaire
          <br>La suppression de son token entraînera la perte définitive de ${item.name}.`)
        return
      }
      return {
        destId: destItemId,
        targetActorId: actor.id,
        itemId: item.id,
        sourceActorId: item.actor?.id,
        sourceTokenId: item.actor?.token?.id,
        srcId: objetVersConteneur[item.id],
        onEnleverConteneur: () => { delete objetVersConteneur[item.id]; },
        onAjouterDansConteneur: (itemId, conteneurId) => { objetVersConteneur[itemId] = conteneurId; }
      }
    }
    else {
      ui.notifications.warn(`Impossible de donner ${item.name} à ${actor.name}: ${item.type} / ${actor.type}`);
    }
    return undefined;
  }

  static async splitItem(item, actor, onSplit = () => { }) {
    const _onSplit = async (item, split) => {
      await RdDSheetUtility._onSplitItem(item, split, actor);
      onSplit();
      await RdDSheetUtility.renderItemBranch(actor, item)
    }
    const dialog = await DialogSplitItem.create(item, _onSplit)
    dialog.render(true)
  }

  static async _onSplitItem(item, split, actor) {
    if (split >= 1 && split < item.system.quantite) {
      await item.diminuerQuantite(split);
      const splitItem = foundry.utils.deepClone(item);
      // todo: ajouter dans le même conteneur?
      splitItem.system.quantite = split;
      await actor.createEmbeddedDocuments('Item', [splitItem])
    }
  }

  static async renderItemBranch(actor, item) {
    while (item) {
      await item.sheet?.render()
      item = actor.findConteneur(item)
    }
  }
}