
-- Import the engine.
modimport("engine.lua")

-- Imports to keep the keyhandler from working while typing in chat.
Load "chatinputscreen"
Load "consolescreen"
Load "textedit"

PrefabFiles = {
	"qiuhaizi",
	"personal_liwuhe_eyebone",
	"personal_liwuhe",
	"bangbangtang",--c_give("bangbangtang")
}

Assets = {
    Asset( "IMAGE", "images/saveslot_portraits/qiuhaizi.tex" ),
    Asset( "ATLAS", "images/saveslot_portraits/qiuhaizi.xml" ),

    Asset( "IMAGE", "images/selectscreen_portraits/qiuhaizi.tex" ),
    Asset( "ATLAS", "images/selectscreen_portraits/qiuhaizi.xml" ),
	
    Asset( "IMAGE", "images/selectscreen_portraits/qiuhaizi_silho.tex" ),
    Asset( "ATLAS", "images/selectscreen_portraits/qiuhaizi_silho.xml" ),

    Asset( "IMAGE", "bigportraits/qiuhaizi.tex" ),
    Asset( "ATLAS", "bigportraits/qiuhaizi.xml" ),
	
	Asset( "IMAGE", "images/map_icons/qiuhaizi.tex" ),
	Asset( "ATLAS", "images/map_icons/qiuhaizi.xml" ),
	
	Asset( "IMAGE", "images/avatars/avatar_qiuhaizi.tex" ),
    Asset( "ATLAS", "images/avatars/avatar_qiuhaizi.xml" ),
	
	Asset( "IMAGE", "images/avatars/avatar_ghost_qiuhaizi.tex" ),
    Asset( "ATLAS", "images/avatars/avatar_ghost_qiuhaizi.xml" ),
	Asset("ANIM", "anim/bangbangtang.zip"),
   	Asset("ATLAS", "images/inventoryimages/bangbangtang.xml"),
	Asset("IMAGE", "images/inventoryimages/bangbangtang.tex"),
	Asset("ANIM", "anim/swap_bangbangtang.zip"),
	Asset("SOUNDPACKAGE", "sound/qiuqiu.fev"),
	Asset("SOUND", "sound/qiuqiu.fsb"),
	Asset("SOUNDPACKAGE", "sound/zhengzhi.fev"),
	Asset("SOUND", "sound/zhengzhi.fsb"),
}

local require = GLOBAL.require
local STRINGS = GLOBAL.STRINGS
local resolvefilepath = GLOBAL.resolvefilepath

local Ingredient = GLOBAL.Ingredient
local RECIPETABS = GLOBAL.RECIPETABS
local Recipe = GLOBAL.Recipe
local TECH = GLOBAL.TECH
GLOBAL.TUNING.qiuhaizi= {}
GLOBAL.TUNING.qiuhaizi.KEYTHREE =  122

--Transformation
local function elemental( inst )
inst:AddComponent("fuel")
inst.components.fuel.fuelvalue = 50
inst.components.fuel.fueltype = "CHEMICAL"
inst:AddTag("elements")
end

AddPrefabPostInit("rocks",elemental)
AddPrefabPostInit("goldnugget",elemental)
AddPrefabPostInit("flint",elemental)
AddPrefabPostInit("moonrocknugget",elemental)
AddPrefabPostInit("marble",elemental)
AddPrefabPostInit("stinger",elemental)
AddPrefabPostInit("spidergland",elemental)
AddPrefabPostInit("houndstooth",elemental)
AddPrefabPostInit("thulecite_pieces",elemental)
AddPrefabPostInit("thulecite",elemental)

local function IrisFn(inst)

local player = GLOBAL.ThePlayer

if inst:HasTag("playerghost") then return end
if inst.transformed then
	inst.SoundEmitter:PlaySound("dontstarve/sanity/creature2/taunt")
	local x, y, z = inst.Transform:GetWorldPosition()
	local fx = SpawnPrefab("lightning")
	fx.Transform:SetPosition(x, y, z)
	SpawnPrefab("statue_transition").Transform:SetPosition(inst:GetPosition():Get())
	inst.components.locomotor.walkspeed = 4
	inst.components.locomotor.runspeed =6
	inst.components.health.absorb = 0.1
	inst.components.combat.damagemultiplier = 0.75+(inst.level)*0.015
	inst.Transform:SetScale(1.5, 1.5, 1.5)
	inst.components.hunger:SetRate(0.25)--75/480=0.156
    inst.entity:AddLight()
	inst.Light:Enable(false)
	inst.SoundEmitter:PlaySound("qiuqiu/bianshen/bianshen1")

else
if inst.level and inst.level>=40 then
--inst.AnimState:SetBuild("irisheart")
	inst.SoundEmitter:PlaySound("dontstarve/sanity/creature2/taunt")
	local x, y, z = inst.Transform:GetWorldPosition()
	local fx = SpawnPrefab("lightning")
	fx.Transform:SetPosition(x, y, z)
	SpawnPrefab("statue_transition_2").Transform:SetPosition(inst:GetPosition():Get())
    --TheWorld:PushEvent("ms_sendlightningstrike",  inst.components.combat.target:GetPosition())
	inst.components.locomotor.walkspeed = 5
	inst.components.locomotor.runspeed = 7
	inst.components.health.absorb = 0.5
	inst.components.combat.damagemultiplier = 0.75+(inst.level)*0.015+0.5
	inst.Transform:SetScale(2, 2, 2)
	inst.components.hunger:SetRate(1.3)
    inst.entity:AddLight()
	inst.Light:Enable(true)
	inst.Light:SetRadius(7)--范围
    inst.Light:SetFalloff(.5)
    inst.Light:SetIntensity(.9)--强度
    inst.Light:SetColour(245/85,85/85,245/85)
	inst.SoundEmitter:PlaySound("qiuqiu/bianshen/bianshen2")
elseif inst.level and inst.level<40 then
   inst.components.talker:Say("需要40级才能解锁该技能")
return false
end
--inst.soundsname = "iris"

--inst.components.talker:Say("I have business to attend to.", 2.5,true) 


end
 
inst.transformed = not inst.transformed

inst.components.health:DoDelta(-20)
return true
 
end
 
AddModRPCHandler("qiuhaizi", "IRIS", IrisFn)

-- An liwuhebone is given every time player is spawned/loaded. It's not saved
local function Giveliwuhebone(inst)
	local liwuhebone = GLOBAL.SpawnPrefab("personal_liwuhe_eyebone")
	if liwuhebone then
		liwuhebone.owner = inst
		inst.liwuhebone = liwuhebone
		inst.components.inventory.ignoresound = true
		inst.components.inventory:GiveItem(liwuhebone)
		inst.components.inventory.ignoresound = false
		liwuhebone.components.named:SetName(inst.name.."'s Eye Bone")
	return liwuhebone
	end
end
local function GetSpawnPoint(pt)
	local theta = math.random() * 2 * GLOBAL.PI
	local radius = 4
	local offset = GLOBAL.FindWalkableOffset(pt, theta, radius, 12, true)
	return offset ~= nil and (pt + offset) or nil
end
local function Personalliwuhe(inst)
	if not inst:HasTag("qiuhaizi") then
		return
	end

	local OnDespawn_prev = inst.OnDespawn
	local OnDespawn_new = function(inst)
		-- Remove liwuhe
		if inst.liwuhe then
			-- Don't allow liwuhe to despawn with irreplaceable items
			inst.liwuhe.components.container:DropEverythingWithTag("irreplaceable")
			
			-- We need time to save before despawning.
			inst.liwuhe:DoTaskInTime(0.1, function(inst)
				if inst and inst:IsValid() then
					inst:Remove()
				end
			end)
			
		end
		
		if inst.liwuhebone then
			-- liwuhebone drops from whatever its in
			local owner = inst.liwuhebone.components.inventoryitem.owner
			if owner then
				-- Remember if liwuhebone is held
				if owner == inst then
					inst.liwuhebone.isheld = true
				else
					inst.liwuhebone.isheld = false
				end
				if owner.components.container then
					owner.components.container:DropItem(inst.liwuhebone)
				elseif owner.components.inventory then
					owner.components.inventory:DropItem(inst.liwuhebone)
				end
			end
			-- Remove liwuhebone
			inst.liwuhebone:DoTaskInTime(0.1, function(inst)
				if inst and inst:IsValid() then
					inst:Remove()
				end
			end)
		else
			print("Error: Player has no linked liwuhebone!")
		end
		if OnDespawn_prev then
			return OnDespawn_prev(inst)
		end
	end
	inst.OnDespawn = OnDespawn_new
	
	local OnSave_prev = inst.OnSave
	local OnSave_new = function(inst, data)
		local references = OnSave_prev and OnSave_prev(inst, data)
		if inst.liwuhe then
			-- Save liwuhe
			local refs = {}
			if not references then
				references = {}
			end
			data.liwuhe, refs = inst.liwuhe:GetSaveRecord()
			if refs then
				for k,v in pairs(refs) do
					table.insert(references, v)
				end 
			end				
		end
		if inst.liwuhebone then
			-- Save liwuhebone
			local refs = {}
			if not references then
				references = {}
			end
			data.liwuhebone, refs = inst.liwuhebone:GetSaveRecord()
			if refs then
				for k,v in pairs(refs) do
					table.insert(references, v)
				end 
			end
			-- Remember if was holding liwuhebone
			if inst.liwuhebone.isheld then
				data.holdingliwuhebone = true
			else
				data.holdingliwuhebone = false
			end
		end
		return references
	end
    inst.OnSave = OnSave_new
	
	local OnLoad_prev = inst.OnLoad
	local OnLoad_new = function(inst, data, newents)
		if data.liwuhe ~= nil then
			-- Load liwuhe
			inst.liwuhe = GLOBAL.SpawnSaveRecord(data.liwuhe, newents)
		else
			--print("Warning: No liwuhe was loaded from save file!")
		end
		
		if data.liwuhebone ~= nil then
			-- Load liwuhe
			inst.liwuhebone = GLOBAL.SpawnSaveRecord(data.liwuhebone, newents)
			
			-- Look for liwuhebone at spawn point and re-equip
			inst:DoTaskInTime(0, function(inst)
				if data.holdingliwuhebone or (inst.liwuhebone and inst:IsNear(inst.liwuhebone,4)) then
					--inst.components.inventory:GiveItem(inst.liwuhebone)
					inst:Returnliwuhebone()
				end
			end)
		else
			print("Warning: No liwuhebone was loaded from save file!")
		end
		
		-- Create new liwuhebone if none loaded
		if not inst.liwuhebone then
			Giveliwuhebone(inst)
		end
		
		inst.liwuhebone.owner = inst
		
		
		if OnLoad_prev then
			return OnLoad_prev(inst, data, newents)
		end
	end
    inst.OnLoad = OnLoad_new
	
	local OnNewSpawn_prev = inst.OnNewSpawn
	local OnNewSpawn_new = function(inst)
		-- Give new liwuhebone. Let liwuhe spawn naturally.
		Giveliwuhebone(inst)
		if OnNewSpawn_prev then
			return OnNewSpawn_prev(inst)
		end
	end
    inst.OnNewSpawn = OnNewSpawn_new
	
	if GLOBAL.TheNet:GetServerGameMode() == "wilderness" then
		local function ondeath(inst, data)
			-- Kill player's liwuhe in wilderness mode :(
			if inst.liwuhe then
				inst.liwuhe.components.health:Kill()
			end
			if inst.liwuhebone then
				inst.liwuhebone:Remove()
			end
		end
		inst:ListenForEvent("death", ondeath)
	end
	
	-- Debug function to return liwuhebone
	inst.Returnliwuhebone = function()
		if inst.liwuhebone and inst.liwuhebone:IsValid() then
			if inst.liwuhebone.components.inventoryitem.owner ~= inst then
				inst.components.inventory:GiveItem(inst.liwuhebone)
			end
		else
			Giveliwuhebone(inst)
		end
		if inst.liwuhe and not inst:IsNear(inst.liwuhe, 20) then
			local pt = inst:GetPosition()
			local spawn_pt = GetSpawnPoint(pt)
			if spawn_pt ~= nil then
				inst.liwuhe.Physics:Teleport(spawn_pt:Get())
				inst.liwuhe:FacePoint(pt:Get())
			end
		end
	end
end

GLOBAL.c_returnliwuhebone = function(inst)
	if not inst then
		inst = GLOBAL.ThePlayer or GLOBAL.AllPlayers[1]
	end
	if not inst or not inst.Returnliwuhebone then 
		print("Error: Cannot return liwuhebone")
		return 
	end
	inst:Returnliwuhebone()
end

AddPlayerPostInit(Personalliwuhe)

--No One Enters Chester cept the one with the liwuhe bone!

local function HasliwuheBone(doer)
    if doer.components.inventory and doer.components.inventory:FindItem(function(item)
            if item.prefab == "personal_liwuhe_eyebone" then return true end
        end) ~= nil then
        return true
    else
        return false
    end
end
 
local oldACTIONSTORE = GLOBAL.ACTIONS.STORE.fn
GLOBAL.ACTIONS.STORE.fn = function(act)
    if act.target and act.target.prefab == "personal_liwuhe" and act.target.components.container ~= nil and act.invobject.components.inventoryitem ~= nil and act.doer.components.inventory ~= nil then
        print(act.doer.name,"is trying to do something with a liwuhe")
        if HasliwuheBone(act.doer) then
            print(act.doer.name,"has liwuhe Bone, proceed")
            return oldACTIONSTORE(act)
        else
            print(act.doer.name,"doesn't has the liwuhe Bone, exit")
            if act.doer.components.talker then act.doer.components.talker:Say("No Can Do!") end
                        return true
        end
    else
        return oldACTIONSTORE(act)
    end
end

local old_RUMMAGE = GLOBAL.ACTIONS.RUMMAGE.fn 
GLOBAL.ACTIONS.RUMMAGE.fn = function(act)
    if act.target and act.target.prefab == "personal_liwuhe" then  
        print("GLOBAL.ACTIONS.RUMMAGE--"..tostring(act.doer.components.inventory))
        result = act.doer.components.inventory:FindItem(function(item)
            if item.prefab == "personal_liwuhe_eyebone" then 
               print("GLOBAL.ACTIONS.RUMMAGE--"..tostring(item).."--ok--") 
               return true
            end
        end)
        if result then 
            return old_RUMMAGE(act)
        else
            print("GLOBAL.ACTIONS.RUMMAGE--"..tostring(item).."--fail--") 
            act.doer:DoTaskInTime(1, function ()
                act.doer.components.talker:Say("No Can Do!")
            end)
            return false
        end
    else
        return old_RUMMAGE(act)
    end
end

----礼物盒

STRINGS.NAMES.PERSONAL_liwuhe = "礼物盒"
STRINGS.NAMES.PERSONAL_liwuhe_EYEBONE = "礼物盒星星"

GLOBAL.STRINGS.NAMES.BANGBANGTANG = "棒棒糖" 
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.GALIENTSWORD = "一把非同寻常的武器!"
-- The character select screen lines
STRINGS.CHARACTER_TITLES.qiuhaizi = "萌萌的吃货"
STRINGS.CHARACTER_NAMES.qiuhaizi = "球孩子"
STRINGS.CHARACTER_DESCRIPTIONS.qiuhaizi = "*变身\n*吃食物升级\n*武器召唤龙卷风"
STRINGS.CHARACTER_QUOTES.qiuhaizi = "\"有人和我一起玩吗\""

-- Custom speech strings
STRINGS.CHARACTERS.qiuhaizi = require "speech_qiuhaizi"

-- The character's name as appears in-game 
STRINGS.NAMES.qiuhaizi = "球孩子"

-- The default responses of examining the character
STRINGS.CHARACTERS.GENERIC.DESCRIBE.qiuhaizi = 
{
	GENERIC = "It's 球孩子!",
	ATTACKER = "That 球孩子 looks shifty...",
	MURDERER = "Murderer!",
	REVIVER = "球孩子, friend of ghosts.",
	GHOST = "球孩子 could use a heart.",
}


AddMinimapAtlas("images/map_icons/qiuhaizi.xml")

-- Add mod character to mod character list. Also specify a gender. Possible genders are MALE, FEMALE, ROBOT, NEUTRAL, and PLURAL.
AddModCharacter("qiuhaizi", "FEMALE")

AddModRPCHandler("qiuhaizi", "qiu", function(player)
	if not player:HasTag("playerghost") and player.prefab == "qiuhaizi"  then
	if player.level and player.level>=60 then
	    if player.components.hunger  and player.components.hunger.current>=50 then
		player.SoundEmitter:PlaySound("zhengzhi/music/zhengzhi")
		player.components.talker:Say("music！")
		player.components.hunger:DoDelta(-50)
		player.is_singing=true
		player:DoTaskInTime(26,function()
		player.is_singing=false
		end)
		else
		player.components.talker:Say("饱食度大于50才能唱歌")
		end
	else
	player.components.talker:Say("需要60级才能解锁该技能")
	end
	end
end)

 local hqghandlers = {}
 
 AddPlayerPostInit(function(inst)
	-- We hack
	inst:DoTaskInTime(0, function()
		-- We check if the character is ourselves
		-- So if another horo player joins, we don't get the handlers
		if inst == GLOBAL.ThePlayer then
			-- If we are horo
			if inst.prefab == "qiuhaizi"   then
				-- We create and store the key handlers
				hqghandlers[120] = TheInput:AddKeyDownHandler(KEY_X, function()
					SendModRPCToServer(MOD_RPC["qiuhaizi"]["qiu"])
				end)
			inst:DoPeriodicTask(1,function()
			if inst.components.health and not inst.components.health:IsDead() and not inst:HasTag("playerghost") then
			local x,y,z=inst.Transform:GetWorldPosition()
			local ents=TheSim:FindEntities(x,y,z,10,{"player"},{"playerghost"})
			for k,v in pairs(ents) do
					if v.components.health and not v.components.health:IsDead()  then
					 
					if v.components.sanity and inst.is_singing then  
					 v.components.sanity:DoDelta(2,true)
					end

					end
				end
			end
			end)

			else
				-- If not, we go to the handlerslist and empty it
				-- This is to avoid having the handlers if we switch characters in wilderness
				-- If it's already empty, nothing changes
				for k, v in pairs(hqghandlers) do
					hqghandlers[k] = nil
				end
			end
		end
	end)
end)


