import {world, system,ItemStack,EntityComponentTypes,EquipmentSlot} from '@minecraft/server'
import {ActionFormData,ModalFormData} from '@minecraft/server-ui'

export default class customisation {
    #ns = "sqst_mnts"
    #colors = {
        "none":0,
        "white": 1,
        "orange": 2,
        "magenta": 3,
        "light_blue": 4,
        "yellow": 5,
        "lime": 6,
        "pink": 7,
        "gray": 8,
        "light_gray": 9,
        "cyan": 10,
        "purple": 11,
        "blue": 12,
        "brown": 13,
        "green": 14,
        "red": 15,
        "black": 16
    }
    constructor () {
        // console.log("customisation")
        world.beforeEvents.playerInteractWithEntity.subscribe(event => {
            let color = event.target?.getProperty("sqst:prp_color1")
            let rider = event.target?.getComponent(EntityComponentTypes.Rideable)?.getRiders()[0]
            if((event?.itemStack?.typeId?.endsWith("_dye")||event?.itemStack?.typeId=="minecraft:water_bucket") && color!==undefined && rider === undefined) {
                event.cancel = true;
                system.run(()=>this.showForm (event)) 
            }
        })
    }

    showForm (event) {
        // create form
        let name = event.target.typeId.slice(this.#ns.length+1)
        let word = event?.itemStack?.typeId=="minecraft:water_bucket"?"Wash":"Dye"
        let skin = event?.target?.getProperty("sqst:prp_skin")
        if(skin===undefined) skin = 0;
        let newForm = new ActionFormData()
        .title({ translate: this.#ns+'.form.title', with: ['\n'] })
        .body({ translate: event?.itemStack?.typeId=="minecraft:water_bucket"?this.#ns+'.form.wbody':this.#ns+'.form.body', with: ['\n'] })
        .button({ translate: this.#ns+'.form.button.'+name+'1', with: [word] },'textures/sqst/mnts/form/'+name+'/part'+skin+'a')
        .button({ translate: this.#ns+'.form.button.'+name+'2', with: [word] },'textures/sqst/mnts/form/'+name+'/part'+skin+'b')
        .button({ translate: this.#ns+'.form.button.'+name+'3', with: [word] },'textures/sqst/mnts/form/'+name+'/part'+skin+'c')

        
        //show form to the player
        newForm.show(event.player).then(formResponse => {
          // player exited the form. Stop and exit the method
          if (formResponse.canceled) return

          if(formResponse.selection!==undefined){
                let color = "none"
                if(event.itemStack.typeId=="minecraft:water_bucket"){
                    //if waterbucket use the water from the bucket
                    event.player.getComponent(EntityComponentTypes.Equippable).setEquipment(EquipmentSlot.Mainhand,new ItemStack("minecraft:bucket",1))
                }else{
                    //if not waterbucket get the color form typeID else color is none
                    const item = event.itemStack.typeId
                    color=item.substring(item.indexOf(":")+1,item.lastIndexOf("_dye"))
                    //if color part of dictionary, remove a item from stack or delete the last item
                    if(color!=undefined && this.#colors[color]!=undefined)
                        if(event.itemStack.amount>1)
                            event.player.getComponent(EntityComponentTypes.Equippable).setEquipment(EquipmentSlot.Mainhand,new ItemStack(event.itemStack.typeId,event.itemStack.amount-1))
                        else   
                            event.player.getComponent(EntityComponentTypes.Equippable).setEquipment(EquipmentSlot.Mainhand,null)
                } 
                //if color part of dictionary, set the color for the selected part
                if(color!=undefined && this.#colors[color]!=undefined){
                    switch(formResponse.selection){
                        case 0 :
                            this.setProp(event.target, "sqst:prp_color1", this.#colors[color])
                            break;
                        case 1 :
                            this.setProp(event.target, "sqst:prp_color2", this.#colors[color])
                            break;
                        case 2 :
                            this.setProp(event.target, "sqst:prp_color3", this.#colors[color])
                            break;
                    }
                }
            }
        })
        .catch(error => {
            console.warn('Failed to show form: ' + error);
            return -1;
        });
      }

      setProp(ent, prop, inputValue){
        try{
          ent.setProperty(prop,inputValue)
          return true
        } catch (error) {
          console.warn(`setProp(${prop}): ${error}`)
          return false
        }
    }
}