import { world,system,ItemStack,GameMode } from "@minecraft/server";
import { VenderOwnerOpen,VenderTradeOpen } from "./vender";

const dyes=[
    'minecraft:light_blue_dye',
    'minecraft:black_dye',
    'minecraft:blue_dye',
    'minecraft:brown_dye',
    'minecraft:gray_dye',
    'minecraft:green_dye',
    'minecraft:cyan_dye',
    'minecraft:lime_dye',
    'minecraft:magenta_dye',
    'minecraft:orange_dye',
    'minecraft:pink_dye',
    'minecraft:purple_dye',
    'minecraft:red_dye',
    'minecraft:light_gray_dye',
    'minecraft:white_dye',
    'minecraft:yellow_dye'
]
function decreaseItemStack(source,itemStack)
{
    const equipment = source.getComponent('equippable')
    if (source.matches({ gameMode: GameMode.Creative })) return;
    if (itemStack.amount > 1) {
        itemStack.amount -= 1;
        equipment.setEquipment('Mainhand', itemStack);
    } else if (itemStack.amount === 1) {
        equipment.setEquipment('Mainhand', undefined);
    }
    
}

world.beforeEvents.playerInteractWithEntity.subscribe(data => {
    let entity = data.target
    let player = data.player; 
    let item = data.itemStack
    if(item?.typeId =="edx:fire_opal_block" && entity.typeId == "edx:blazeblade_off")
    {
        system.runTimeout(() => {
            entity.triggerEvent('start_revive')
            decreaseItemStack(player,item)
        })
    }
    else if(item?.typeId =="edx:soul_in_bottle" && entity.typeId == "edx:blazeblade_off" && world?.getDynamicProperty('void_mode')==true)
    {
        data.cancel=true
        system.runTimeout(() => {
            entity.triggerEvent('soul_start_revive')
            decreaseItemStack(player,item)
        })
        
    }
    else if(entity.typeId == "edx:blazeblade_off")
    {
        var FireOpalInteractMessage= {rawtext :[{ 
    translate: "message.interact.FireOpal",
  }]};
        player.sendMessage(FireOpalInteractMessage); 
    }
    else if(entity.typeId == "edx:blazeblade_dead" && item?.typeId !="minecraft:blaze_rod")
    {
        var BlazeRodInteractMessage= {rawtext :[{ 
            translate: "message.interact.BlazeRod",
        }]};
        player.sendMessage(BlazeRodInteractMessage); 
    }
    else if(entity.typeId == "edx:blazeblade_dead" && item?.typeId =="minecraft:blaze_rod")
    {
        if(entity.getProperty('edx:power')!=5)
            system.runTimeout(() => {
            if(entity.getProperty('edx:power')==undefined)
                entity.setProperty('edx:power',0)
            entity.setProperty('edx:power',entity.getProperty('edx:power')+1)
            })
        else
            system.runTimeout(() => {
             entity.triggerEvent('revive')
            })
        const equipment = player.getComponent('equippable');
        system.runTimeout(() => {
            entity.dimension.playSound('mob.blaze.breathe',entity.location);
            entity.dimension.spawnParticle('edx:blazeblade_dead_fuel',entity.location)
            decreaseItemStack(player,equipment,item)
        })
    }
    else if(item?.typeId =="minecraft:shears" && entity.getProperty('edx:is_chested'))
    {
        var itemList =[]
        const inv = entity.getComponent('minecraft:inventory').container
        for (var i=0;i<9;i++){
            var newItem=inv.getItem(i);
            if(newItem!=undefined)
                itemList.push(newItem)
        }
        system.runTimeout(() => {
            for (var i=0;i<itemList.length;i++){
                entity.dimension.spawnItem(itemList[i],entity.location)
            }
        })
       
    }
    if (entity.typeId === "minecraft:player" && item.typeId == "edx:double_soulbound_ring" && item.getLore().length==0 ) { 
        system.runTimeout(() => {
            player.dimension.playSound('lodestone_compass.link_compass_to_lodestone',player.location);
            var newitem = new ItemStack('edx:soulbound_ring', 1)
            newitem.setLore([entity.name])
            newitem.setDynamicProperty('id',entity.id)
            player.getComponent('equippable').setEquipment('Mainhand',newitem);
            entity.dimension.playSound('lodestone_compass.link_compass_to_lodestone',entity.location);
            
            newitem = new ItemStack('edx:soulbound_ring', 1)
            newitem.setLore([player.name])
            newitem.setDynamicProperty('id',player.id)
            system.runTimeout(() => {
            entity.dimension.spawnItem(newitem, entity.location);
                            },2)   
        })
    }
    else if(entity.typeId == "edx:personal_vender"){
        
        if(entity.getDynamicProperty("owner") == player.name)
        {
           if(dyes.indexOf(item?.typeId)!=-1 && dyes.indexOf(item?.typeId)!=entity.getProperty("edx:color"))
           {
            system.runTimeout(() => {
                player.playSound('sign.dye.use')
                entity.setProperty("edx:color",dyes.indexOf(item?.typeId))
                decreaseItemStack(player,item)
                
            })
            return
           }
           if(player.isSneaking)
           {
            system.runTimeout(() => {
                VenderOwnerOpen(player,entity,item)
            })
           }
        }
        if(!player.isSneaking)
        {
            system.runTimeout(() => {
                if(entity.getProperty("edx:open"))
                {
                    VenderTradeOpen(player,entity)
                }
                else
                {
                var VenderTradeCloseInteractMessage= { 
                 translate: "message.interact.VenderTradeClose",
                };
                    player.sendMessage(VenderTradeCloseInteractMessage); 
                }
            })
        }
        else
        {
            if(entity.getDynamicProperty("owner") != player.name)
            {
                const random = Math.random()
                if(random>0.05)
                {
                    var Vender1InteractMessage= {rawtext :[{ 
                 translate: "message.interact.Vender1",
                }]};
                    var Vender2InteractMessage= {rawtext :[{ 
                 translate: "message.interact.Vender2",
                }]};
                    player.sendMessage(`${Vender1InteractMessage} ${entity.getDynamicProperty("owner")} ${Vender2InteractMessage}`);
                }
                else
                {
                 var YouAreNotTheFatherInteractMessage= {rawtext :[{ 
                 translate: "message.interact.YouAreNotTheFatherInteractMessage",
                }]};
                    player.sendMessage(YouAreNotTheFatherInteractMessage);
                }
            }
        }
        
    }
}
)