/**
 * Extend the basic ActorSheet with some very simple modifications
 * @extends {ActorSheet}
 */

import { PegasusUtility } from "./pegasus-utility.js"
import { PegasusRollDialog } from "./pegasus-roll-dialog.js"

/* -------------------------------------------- */
export class PegasusVehicleSheet extends ActorSheet {

  /** @override */
  static get defaultOptions() {

    return mergeObject(super.defaultOptions, {
      classes: ["fvtt-pegasus-rpg", "sheet", "actor"],
      template: "systems/fvtt-pegasus-rpg/templates/vehicle-sheet.html",
      width: 960,
      height: 720,
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "combat" }],
      dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
      editScore: true
    });
  }

  /* -------------------------------------------- */
  async getData() {
    const objectData = this.object    
    let actorData = duplicate(this.object)

    let formData = {
      title: this.title,
      id: objectData.id,
      type: objectData.type,
      img: objectData.img,
      name: objectData.name,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      data: actorData.system,
      effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
      limited: this.object.limited,
      optionsDiceList: PegasusUtility.getOptionsDiceList(),
      vmsAvailable: objectData.system.modules.totalvms - objectData.system.modules.vmsused,
      crewList: this.actor.getCrewList(),
      totalCost: this.actor.getTotalCost(),
      optionsLevel: PegasusUtility.getOptionsLevel(),
      subActors: duplicate(this.actor.getSubActors()),
      effects: duplicate(this.actor.getEffects()),
      combatModules: duplicate(this.actor.getCombatModules()),
      powerCoreModules: duplicate(this.actor.getPowercoreModules()),
      vehicleHull: duplicate(this.actor.getVehicleHull()),
      mobilityModules: duplicate(this.actor.getMobilityModules()),
      propulsionModules: duplicate(this.actor.getPropulsionModules()),
      vehicleModules: this.actor.checkAndPrepareEquipments(duplicate(this.actor.getVehicleModules())),
      vehicleWeaponModules: this.actor.checkAndPrepareEquipments(duplicate(this.actor.getVehicleWeaponModules())),
      cargos: this.actor.checkAndPrepareEquipments(duplicate(this.actor.getCargos()) ),
      cargoCurrent: this.actor.getCurrentCargoCapacity(),
      moneys: duplicate(this.actor.getMoneys()),
      options: this.options,
      owner: this.document.isOwner,
      editScore: this.options.editScore,
      isGM: game.user.isGM
    }
    this.formData = formData;

    console.log("VEHICLE : ", formData, this.object);
    return formData;
  }

  /* -------------------------------------------- */
  async openGenericRoll() {
    let rollData = PegasusUtility.initGenericRoll()
    rollData.traumaState = this.actor.getTraumaState()
    
    let rollDialog = await PegasusRollDialog.create( this.actor, rollData);
    rollDialog.render( true );
  }

  /* -------------------------------------------- */
  async rollIDR( itemId, diceValue) { 
    let item = this.actor.items.get( itemId) ?? {name: "Unknown"}
    let myRoll = new Roll(diceValue+"x").roll({ async: false })
    await PegasusUtility.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
    let chatData = {
      user: game.user.id,
      rollMode: game.settings.get("core", "rollMode"),
      whisper: [game.user.id].concat(ChatMessage.getWhisperRecipients('GM')),
      content: `${this.actor.name} has roll IDR for ${item.name} : ${myRoll.total}`
    }
    ChatMessage.create(chatData)
  }

  /* -------------------------------------------- */
  /** @override */
  activateListeners(html) {
    super.activateListeners(html);

    // Everything below here is only needed if the sheet is editable
    if (!this.options.editable) return;
    
    html.bind("keydown", function(e) { // Ignore Enter in actores sheet
      if (e.keyCode === 13) return false;
    });  

    // Update Inventory Item
    html.find('.item-edit').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      let itemId = li.data("item-id")
      const item = this.actor.items.get( itemId );
      item.sheet.render(true);
    });
    // Delete Inventory Item
    html.find('.item-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      PegasusUtility.confirmDelete(this, li)
    })
    html.find('.item-add').click(ev => {
      let dataType = $(ev.currentTarget).data("type")
      this.actor.createEmbeddedDocuments('Item', [{ name: "NewItem", type: dataType }], { renderSheet: true })
    })
        
    html.find('.current-speed-change').change(ev => {
      let speed = ev.currentTarget.value
      this.actor.manageCurrentSpeed(speed)
    })

    html.find('.vehicle-module-activate').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      let itemId = li.data("item-id")
      this.actor.activateVehicleModule( itemId)
    });      
    html.find('.vehicle-weapon-activate').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      let itemId = li.data("item-id")
      this.actor.activateVehicleModule( itemId)
    });      
        html.find('.effect-used').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      let itemId = li.data("item-id");
      this.actor.perkEffectUsed( itemId)
    });      
        
    html.find('.member-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      let actorId = li.data("actor-id")
      this.actor.delCrew(actorId)
    });
    
    html.find('.quantity-minus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.incDecQuantity( li.data("item-id"), -1 );
    } )
    html.find('.quantity-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.incDecQuantity( li.data("item-id"), +1 );
    } )
    html.find('.vehicle-current-nrg-minus').click(event => {
      this.actor.incDecNRG( -1 );
    } )
    html.find('.vehicle-current-nrg-plus').click(event => {
      this.actor.incDecNRG( 1 );
    } )
    
    html.find('.ammo-minus').click(event => {
      const li = $(event.currentTarget).parents(".item")
      this.actor.incDecAmmo( li.data("item-id"), -1 );
    } );
    html.find('.ammo-plus').click(event => {
      const li = $(event.currentTarget).parents(".item")
      this.actor.incDecAmmo( li.data("item-id"), +1 )
    } );

    html.find('.vehicle-stun-minus').click(event => {
      this.actor.modifyVehicleStun( -1 )
    } )
    html.find('.vehicle-stun-plus').click(event => {
      this.actor.modifyVehicleStun( 1 )
    } )

    
    html.find('.momentum-minus').click(event => {
      this.actor.modifyMomentum( -1 )
    } )
    html.find('.momentum-plus').click(event => {
      this.actor.modifyMomentum( 1 )
    } )

    html.find('.unarmed-attack').click((event) => {
      this.actor.rollUnarmedAttack();
    });
    html.find('.generic-pool-roll').click((event) => {      
      this.openGenericRoll()
    } );

    html.find('.attack-melee').click((event) => {
      this.actor.rollPoolFromVehicle( 'com', false, "melee-atk")
    });
    html.find('.damage-melee').click((event) => {
      this.actor.rollPoolFromVehicle( 'str', false, "melee-dmg")
    });
    html.find('.attack-ranged').click((event) => {
      this.actor.rollPoolFromVehicle( 'agi', false, "ranged-atk")
    });
    html.find('.damage-ranged').click((event) => {
      this.actor.rollPoolFromVehicle( 'per', false, "ranged-dmg");
    });
    html.find('.defense-roll').click((event) => {
      this.actor.rollPoolFromVehicle( 'agi', true, "defence");
    });
    html.find('.damage-resistance').click((event) => {
      this.actor.rollVehicleDamageResistance( );
    });
    html.find('.currentlevel-change').change((event) => {
      const statKey = $(event.currentTarget).data("stat-key");
      if ( statKey == "man") {
        this.actor.setTurningArc(event.currentTarget.value)  
      }
      if ( statKey == "pc") {
        this.actor.updateMaxNrg(event.currentTarget.value)  
      }
    })
            
    html.find('.roll-stat').click((event) => {
      const statId = $(event.currentTarget).data("stat-key");
      this.actor.rollStat(statId);
    });
    html.find('.roll-mr').click((event) => {
      this.actor.rollMR();
    });
    html.find('.roll-idr').click((event) => {
      const diceValue = $(event.currentTarget).data("dice-value")
      const li = $(event.currentTarget).parents(".item")
      this.rollIDR( li.data("item-id"), diceValue)
    })    
    
    html.find('.weapon-roll').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weaponId = li.data("item-id");
      this.actor.rollWeapon(weaponId);
    });
    html.find('.armor-roll').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const armorId = li.data("item-id");
      this.actor.rollArmor(armorId);
    });
    
    html.find('.weapon-damage-roll').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weaponId = li.data("item-id");
      this.actor.rollWeapon(weaponId, true);
    });
    
    html.find('.weapon-damage').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.getOwnedItem(li.data("item-id"));
      this.actor.rollDamage(weapon, 'damage');
    });
    
    html.find('.lock-unlock-sheet').click((event) => {
      this.options.editScore = !this.options.editScore;
      this.render(true);
    });    
    html.find('.item-link a').click((event) => {
      const itemId = $(event.currentTarget).data("item-id");
      const item = this.actor.getOwnedItem(itemId);
      item.sheet.render(true);
    });    
    html.find('.item-equip').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      this.actor.equipItem( li.data("item-id") );
      this.render(true);      
    });

    html.find('.update-field').change(ev => {
      const fieldName = $(ev.currentTarget).data("field-name");
      let value = Number(ev.currentTarget.value);
      this.actor.update( { [`${fieldName}`]: value } );
    })

    html.find('.member-view').click((event) => {
      const li = $(event.currentTarget).parents(".item")
      let actorId = li.data("actor-id")
      const actor = game.actors.get( actorId )
      actor.sheet.render(true)
    })
  }
  
  /* -------------------------------------------- */
  /** @override */
  setPosition(options = {}) {
    const position = super.setPosition(options);
    const sheetBody = this.element.find(".sheet-body");
    const bodyHeight = position.height - 192;
    sheetBody.css("height", bodyHeight);
    return position;
  }

  /* -------------------------------------------- */
  async _onDropItem(event, dragData) {
    const item = fromUuidSync(dragData.uuid)
    if (item == undefined) {
      item = this.actor.items.get( dragData.uuid )
    }
    let itemFull = await PegasusUtility.searchItem( item )
    let ret = await this.actor.preprocessItemVehicle( event, itemFull, true )
    if ( ret ) {
      super._onDropItem(event, dragData)
    }
  }

  /* -------------------------------------------- */
  async _onDropActor(event, dragData) {
    const actor = fromUuidSync(dragData.uuid)
    if (actor) { 
      this.actor.addCrew(actor.id)
    }else {
      ui.notifications.warn("This actor is not found and can't be added to the Vehicle's crew.")
    }
    super._onDropActor(event)
  }

  /* -------------------------------------------- */
  /** @override */
  _updateObject(event, formData) {
    // Update the Actor
    return this.object.update(formData)
  }
}
