local MakePlayerCharacter = require "prefabs/player_common"


local assets = {

        Asset( "ANIM", "anim/player_basic.zip" ),
        Asset( "ANIM", "anim/player_idles_shiver.zip" ),
        Asset( "ANIM", "anim/player_actions.zip" ),
        Asset( "ANIM", "anim/player_actions_axe.zip" ),
        Asset( "ANIM", "anim/player_actions_pickaxe.zip" ),
        Asset( "ANIM", "anim/player_actions_shovel.zip" ),
        Asset( "ANIM", "anim/player_actions_blowdart.zip" ),
        Asset( "ANIM", "anim/player_actions_eat.zip" ),
        Asset( "ANIM", "anim/player_actions_item.zip" ),
        Asset( "ANIM", "anim/player_actions_uniqueitem.zip" ),
        Asset( "ANIM", "anim/player_actions_bugnet.zip" ),
        Asset( "ANIM", "anim/player_actions_fishing.zip" ),
        Asset( "ANIM", "anim/player_actions_boomerang.zip" ),
        Asset( "ANIM", "anim/player_bush_hat.zip" ),
        Asset( "ANIM", "anim/player_attacks.zip" ),
        Asset( "ANIM", "anim/player_idles.zip" ),
        Asset( "ANIM", "anim/player_rebirth.zip" ),
        Asset( "ANIM", "anim/player_jump.zip" ),
        Asset( "ANIM", "anim/player_amulet_resurrect.zip" ),
        Asset( "ANIM", "anim/player_teleport.zip" ),
        Asset( "ANIM", "anim/wilson_fx.zip" ),
        Asset( "ANIM", "anim/player_one_man_band.zip" ),
        Asset( "ANIM", "anim/shadow_hands.zip" ),
        Asset( "SOUND", "sound/sfx.fsb" ),
        Asset( "SOUND", "sound/wilson.fsb" ),
        Asset( "ANIM", "anim/beard.zip" ),

        Asset( "ANIM", "anim/faroz.zip" ),
        Asset( "ANIM", "anim/ghost_faroz_build.zip" ),
}
local prefabs = {}
local start_inv = {
    -- Custom starting items
    "faroz_gls",
}

local function applyupgrades(inst)

    local max_upgrades = 30
    local upgrades = math.min(inst.level, max_upgrades)

    local hunger_percent = inst.components.hunger:GetPercent()
    local health_percent = inst.components.health:GetPercent()
    local sanity_percent = inst.components.sanity:GetPercent()

    inst.components.hunger.max = math.ceil (70 + upgrades * 2) --130
    inst.components.health.maxhealth = math.ceil (70 + upgrades * 2) --130
    inst.components.sanity.max = math.ceil (70 + upgrades * 3) --160
    
    inst.components.locomotor.walkspeed =  math.ceil (7 + upgrades / 7) --11
    inst.components.locomotor.runspeed = math.ceil (9 + upgrades / 6) --14
      if TheWorld.state.issummer or (inst.components.temperature.current > 40) then
    inst.components.temperature.inherentinsulation = 0
    else
    inst.components.temperature.inherentinsulation = upgrades * upgrades
    end
    
    
    inst.components.talker:Say("Level : ".. (inst.level))
    
    if inst.level >29 then
        inst.components.talker:Say("Level : Max!")
                inst.components.builder.science_bonus = 2
    end

    inst.components.hunger:SetPercent(hunger_percent)
    inst.components.health:SetPercent(health_percent)
    inst.components.sanity:SetPercent(sanity_percent)

end

local function oneat(inst, food)
    
    --if food and food.components.edible and food.components.edible.foodtype == "HELLO" then
    if food and food.components.edible and food.prefab == "corn" or food.prefab == "carrot" then
        --give an upgrade!
        inst.level = inst.level + 1
        applyupgrades(inst) 
        inst.SoundEmitter:PlaySound("dontstarve/characters/wx78/levelup")

    end
end

local function onpreload(inst, data)
    if data then
        if data.level then
            inst.level = data.level
            applyupgrades(inst)
            --re-set these from the save data, because of load-order clipping issues
            if data.health and data.health.health then inst.components.health.currenthealth = data.health.health end
            if data.hunger and data.hunger.hunger then inst.components.hunger.current = data.hunger.hunger end
            if data.sanity and data.sanity.current then inst.components.sanity.current = data.sanity.current end
            inst.components.health:DoDelta(0)
            inst.components.hunger:DoDelta(0)
            inst.components.sanity:DoDelta(0)
        end
    end

end

local function onsave(inst, data)
    data.level = inst.level
    data.charge_time = inst.charge_time
end

-- This initializes for both clients and the host
local common_postinit = function(inst) 
    -- choose which sounds this character will play
    inst.soundsname = "willow"

    -- Minimap icon
    inst.MiniMapEntity:SetIcon( "faroz.tex" )
    inst:AddComponent("keyhandler")
    --inst:AddComponent("sa_keyhandler")
    inst.components.keyhandler:AddActionListener("faroz", KEY_V, "KEY_V")
    inst.components.keyhandler:AddActionListener("faroz", KEY_F4, "z_skill")
    
end


local function KEY_Vfn(inst)   --Î»ÒÆ
local fin = true
    local x , y , z = TheInputProxy:GetOSCursorPos()
      local p = TheInput:GetWorldPosition(x, y,z) 
      local pos = p
      local fin = false

   if not inst:HasTag("forcefield")  then
   if not  inst.sexycooldown  then
    if not inst:HasTag("playerghost") then
   if  TheWorld.Map:IsAboveGroundAtPoint(pos:Get()) and not pos ~= nil then
                inst.components.locomotor:Stop()
            inst.components.playercontroller:Enable(false) 
   inst.components.sanity:DoDelta(-1)
               inst.components.health:SetInvincible(true)
             --inst.SoundEmitter:PlaySound("dontstarve/zg/willow/pound")
   inst.sexycooldown = true

    inst:Hide()
    inst.SoundEmitter:PlaySound("dontstarve/common/staff_blink")
    SpawnPrefab("small_puff").Transform:SetPosition(inst.Transform:GetWorldPosition())
    inst:DoTaskInTime(0.35, function(inst) 

 
    SpawnPrefab("small_puff").Transform:SetPosition(inst.Transform:GetWorldPosition())
    inst.SoundEmitter:PlaySound("dontstarve/common/staff_blink")

           inst.Transform:SetPosition(TheInput:GetWorldPosition():Get())
    inst:Show()
    inst:RemoveTag("forcefield")
                  inst.components.health:SetInvincible(false)
    inst.components.playercontroller:Enable(true)
 inst.sexycooldown = false
end )


           else
               inst.components.talker:Say("There's no way")
            end
           else
               inst.components.talker:Say("I'm death")
            end
           else
               
            end
                       else
               
            end

end
AddModRPCHandler("faroz", "KEY_V", KEY_Vfn)



local function z_skill(inst)  --±ù¶³Êõ,°Ù²½±ù·â


         local max_upgrades = 30
     local upgrades = math.min(inst.level, max_upgrades) 
local num = inst.components.sanity and inst.components.sanity.current

            if not inst.chargeincooldown then
    if  num and num > (10+upgrades/3) then 
    if not inst:HasTag("playerghost") then

---if inst.components.hunger then

               if not inst:HasTag("forcefield")  then
   inst.chargeincooldown = true

                    inst.sg:GoToState("castspell")
                    if not inst:HasTag("sound")  then
             inst.SoundEmitter:PlaySound("dontstarve/zg/willow/pound")
              inst:AddTag("sound")
inst:DoTaskInTime(1.5, function()
                     inst:RemoveTag("sound")                          
                                             
          
            end)
else
end
                                              
                        local pt = inst:GetPosition()

  
        local v4 = SpawnPrefab("faroz")
        local v1 = SpawnPrefab("faroz")
        local v2 = SpawnPrefab("faroz")
        local v3 = SpawnPrefab("snowball")
         


      local pos = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10)))
      local pos1 = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10)))
      local pos2 = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10)))


      --if not TheWorld.Map:IsAboveGroundAtPoint(pos:Get()) then
       
   -- end

       while ( not TheWorld.Map:IsAboveGroundAtPoint(pos:Get())) do
  
pos = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10)))
     end   

        while ( not TheWorld.Map:IsAboveGroundAtPoint(pos1:Get())) do
 pos1 = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10))) 
       
     end
        while ( not TheWorld.Map:IsAboveGroundAtPoint(pos2:Get())) do
pos2 = Vector3(pt.x+(math.random(10)-math.random(10)), 0, pt.z+(math.random(10)-math.random(10)))

     end

            inst.components.sanity:DoDelta(-10-upgrades/3)
            inst.components.health:SetInvincible(true)
            local fireringfx = SpawnPrefab("firering_fx")
            local groundpoundringfx = SpawnPrefab("groundpoundring_fx")

            fireringfx.Transform:SetPosition(inst.Transform:GetWorldPosition())
            fireringfx.Transform:SetRotation(inst.Transform:GetRotation())
            
            groundpoundringfx.Transform:SetPosition(inst.Transform:GetWorldPosition())
            groundpoundringfx.Transform:SetRotation(inst.Transform:GetRotation())

                    inst.components.talker:Say("天上地下！唯我独尊")
           if not TheWorld.state.issnowing then
        TheSim:ShowAnimOnEntitiesWithTag("SnowCovered", "snow")
           end
        inst:AddTag("forcefield")
        local fx = SpawnPrefab("forcefieldfx")
        fx.entity:SetParent(inst.entity)
        fx.Transform:SetPosition(0, 0.2, 0)
        local fx_hitanim = function()
            fx.AnimState:PlayAnimation("hit")
            fx.AnimState:PushAnimation("idle_loop")
        end
        fx:ListenForEvent("blocked", fx_hitanim, inst)
        inst.active = true

inst:DoTaskInTime(0, function(inst)

inst:DoTaskInTime(0, function(inst)
    inst:StartThread(function()

        for i = 0, 16 do

        for i = 0, 30 do
                                local v3 = SpawnPrefab("snowball")


                local R1 = 25



         local   rad3 = math.random()*2*PI
     local   k3 = math.random()
     local r3 = math.sqrt(k3)*R1
       local x3 = math.sin(rad3)* r3
      local  y3 = math.cos(rad3)* r3
      v3.Transform:SetPosition(x3 + pt.x, 15, y3 + pt.z)


inst:DoTaskInTime(1.2, function(inst)

       v3:Remove()
      end)
      end
 Sleep(0.3)

      end
      end)
  return true          
             end)

   -- end
     


                                        local range = 30
                                local pos3 = Vector3(inst.Transform:GetWorldPosition())
                                local ents1 = TheSim:FindEntities(pos3.x,pos3.y,pos3.z, range)
                                            local s1, s2, s3 = inst.Transform:GetWorldPosition()
            local ents = TheNet:GetPVPEnabled() and
                        TheSim:FindEntities(s1, s2, s3, range, nil, { "playerghost" }, { "sleeper", "player" }) or
                        TheSim:FindEntities(s1, s2, s3, range, { "sleeper" }, { "player" })

          
           -- local ents = TheNet:GetPVPEnabled() and TheSim:FindEntities(pos3.x,pos3.y,pos3.z, nil, { "playerghost" }, { "sleeper", "player" }) or TheSim:FindEntities(pos3.x,pos3.y,pos3.z, { "sleeper" }, { "player" })
            for i, v in ipairs(ents) do
                if v ~= inst and
                    not (v.components.freezable ~= nil and v.components.freezable:IsFrozen()) and
                    not (v.components.pinnable ~= nil and v.components.pinnable:IsStuck()) then
                    if v.components.sleeper ~= nil then
                        v.components.sleeper:AddSleepiness(10, 20)
                    elseif v.components.grogginess ~= nil then
                        v.components.grogginess:AddGrogginess(10, 20)
                    else
                        v:PushEvent("knockedout")
                    end
                end
            end





                        inst:DoTaskInTime(2.5, function()

            fx:RemoveEventCallback("blocked", fx_hitanim, inst)
            fx.kill_fx(fx)
            
            if inst:IsValid() then
               
               -- inst:RemoveTag("forcefield")

                --inst:DoTaskInTime(0.2, function()
                inst.active = false


           
            end
                        inst:Hide()


                        inst:DoTaskInTime(1.5, function(inst)
       -- inst.SoundEmitter:PlaySound("dontstarve/zg/willow/pound")

            
                local fxtable = {"sanity_raise","sanity_lower","statue_transition","statue_transition_2","shadow_despawn"}
                inst:StartThread(function()
                    for k,v in pairs(ents1) do
                            if not v:HasTag("deciduoustree") and (v:HasTag("monster") or v:HasTag("hostile") or v:HasTag("zg_butterfly") or v:HasTag("animal") or v:HasTag("frog") or v:HasTag("rabbit") or v:HasTag("bird") or v:HasTag("zg_icepig") or v:HasTag("shadowboss") or v:HasTag("notraptrigger") or v:HasTag("zg_frog") or v:HasTag("zg_frog0") or v:HasTag("zg_frog1") or v.prefab == "beefalo" or v.prefab == "babybeefalo" or v.prefab == "bunnyman" or v.prefab == "pigguard" or v.prefab == "merm" or v.prefab == "monkey" or v.prefab == "tallbird" or v.prefab == "walrus" or v.prefab == "little_walrus" or v.prefab == "wasphive" or v.prefab == "koalefant_summer" or v.prefab == "koalefant_winter" or v.prefab == "lureplant" or v.prefab == "penguin" or v.prefab == "perd" or v.prefab == "rocky" or v.prefab == "slurper" or v.prefab == "snurtle" or v.prefab == "slurtle" or v.prefab == "slurtlehole") then
                                       -- if upgrade ~= nil then
                                        --if v:HasTag("monster") or v:HasTag("zg_butterfly") or v:HasTag("animal") or v:HasTag("frog") or v:HasTag("rabbit") or v:HasTag("bird") or v:HasTag("zg_icepig") or v:HasTag("shadowboss") or v:HasTag("notraptrigger") or v:HasTag("zg_frog") or v:HasTag("zg_frog0") or v:HasTag("zg_frog1") or v.prefab == "beefalo" or v.prefab == "babybeefalo" or v.prefab == "bunnyman" or v.prefab == "pigguard" or v.prefab == "merm" or v.prefab == "monkey" or v.prefab == "tallbird" or v.prefab == "walrus" or v.prefab == "little_walrus" or v.prefab == "wasphive" or v.prefab == "beehive" or v.prefab == "koalefant_summer" or v.prefab == "koalefant_winter" or v.prefab == "lureplant" or v.prefab == "penguin" or v.prefab == "perd" or v.prefab == "rocky" or v.prefab == "slurper" or v.prefab == "snurtle" or v.prefab == "slurtle" or v.prefab == "slurtlehole" then
                                        if not v.components.health:IsDead() then

                                            local num1 = v.components.health and v.components.health.current
                                            local h = v:GetPosition()

                                            if  TheWorld.state.isswinter then
                                       v.components.health:DoDelta((- 125 - upgrades * 8)*2)
                                       if not inst:HasTag("sound")  then
             inst.SoundEmitter:PlaySound("dontstarve/zg/ch_luffy/call")
              inst:AddTag("sound")
inst:DoTaskInTime(1.5, function()
                     inst:RemoveTag("sound")                          
                                             
          
            end)
else
end
                                        SpawnPrefab(fxtable[math.random(#fxtable)]).Transform:SetPosition(Vector3(v.Transform:GetWorldPosition()):Get())
                                        if  v.components.health:IsDead() then
                                            local os = SpawnPrefab("ice")
                                            os.Transform:SetPosition(h.x, 0, h.z)

                                        end
                                            else
                                        v.components.health:DoDelta(- 125 - upgrades * 8)
                                        if not inst:HasTag("sound")  then
             inst.SoundEmitter:PlaySound("dontstarve/zg/ch_luffy/call")
              inst:AddTag("sound")
inst:DoTaskInTime(1.5, function()
                     inst:RemoveTag("sound")                          
                                             
          
            end)
else
end
                                        SpawnPrefab(fxtable[math.random(#fxtable)]).Transform:SetPosition(Vector3(v.Transform:GetWorldPosition()):Get())
                                        if  v.components.health:IsDead() then
                                               local os = SpawnPrefab("ice")
                                            os.Transform:SetPosition(h.x, 0, h.z)
                                        end
                                           end
                            --
                                         Sleep(0)
                                        end
                                        end
                                        if v.components.freezable and not v:HasTag("player")  then
                                       
                                        v.components.freezable:AddColdness(15 + upgrades/3)
                                        v.components.freezable:SpawnShatterFX()
                                        end
                      
                                        if v.components.burnable ~= nil and v.components.burnable:IsBurning() then
                                        v.components.burnable:Extinguish()
                                        end

                        --if v.Transform then
                            --SpawnPrefab(fxtable[math.random(#fxtable)]).Transform:SetPosition(Vector3(v.Transform:GetWorldPosition()):Get())
                            --Sleep(0)
                       -- end
                    end
                end)
            return true
            end)

                         




      if not (TheWorld.Map:IsAboveGroundAtPoint(pos:Get()) and TheWorld.Map:IsAboveGroundAtPoint(pos1:Get()) and TheWorld.Map:IsAboveGroundAtPoint(pos2:Get())) then

      else

    v4.Transform:SetPosition(pos.x, 0, pos.z)
    v4.sg:GoToState("book")

   v1.Transform:SetPosition(pos1.x, 0, pos1.z)
   v1.sg:GoToState("book")

    v2.Transform:SetPosition(pos2.x, 0, pos2.z)
    v2.sg:GoToState("book")

          
                  



                        inst:DoTaskInTime(2.5, function()

                                        inst:RemoveTag("forcefield")
                                         if not TheWorld.state.isswinter then
            TheSim:HideAnimOnEntitiesWithTag("SnowCovered", "snow")
            end
                                        
 
                                    v4:Remove()
                                     v1:Remove()
                                     v2:Remove()
                                    
                                     end)
                    

 
                                         
            inst:DoTaskInTime(2.5, function()
                                  if math.random()<.33 then
                                     
                        inst.Transform:SetPosition(pos.x, 0, pos.z)
                        inst:Show()

                        elseif math.random()<.66 then
                           
                            inst.Transform:SetPosition(pos1.x, 0, pos1.z)
                            inst:Show()

                        else
                            
                            inst.Transform:SetPosition(pos2.x, 0, pos2.z)
                            inst:Show()

                        end
                        inst.components.health:SetInvincible(false)

            end)           
                    
     





          

            end


            inst:DoTaskInTime(30 - upgrades, function()
                inst.components.talker:Say("冰雪风暴cd结束")
                inst.chargeincooldown = false
            end)
            end)
end)

            else
              inst.components.talker:Say("我正在使用魔法")
            end
            else
              --inst.components.talker:Say("I'm dead")
            end
            else
              inst.components.talker:Say("没有足够的精神值")
            end
            else
               inst.components.talker:Say("技能冷却中")
            end
end
AddModRPCHandler("faroz", "z_skill", z_skill)



-- This initializes for the host only
local master_postinit = function(inst)

    inst.level = 0
    inst.components.eater:SetOnEatFn(oneat)
    applyupgrades(inst)
    -- Stats    
    inst.components.health:SetMaxHealth(70)
    inst.components.hunger:SetMax(70)
    inst.components.sanity:SetMax(70)
    inst.components.sanity.dapperness = (TUNING.DAPPERNESS_HUGE * 2)
    inst.components.locomotor.walkspeed = 7
    inst.components.locomotor.runspeed = 9
    inst.components.combat.damagemultiplier = 1
    --inst.components.sanity.dapperness = 1
    
    inst.OnSave = onsave
    inst.OnPreLoad = onpreload
end

return MakePlayerCharacter("faroz", prefabs, assets, common_postinit, master_postinit, start_inv)