local require = GLOBAL.require
local Ingredient = GLOBAL.Ingredient
local RECIPETABS = GLOBAL.RECIPETABS
local Recipe = GLOBAL.Recipe
local STRINGS = GLOBAL.STRINGS
local ACTIONS = GLOBAL.ACTIONS
local TECH = GLOBAL.TECH
local SpawnPrefab = GLOBAL.SpawnPrefab
GLOBAL.setmetatable(env,{__index=function(t,k) return GLOBAL.rawget(GLOBAL,k) end})
PrefabFiles = {
	"bulingbuling",
	"buling_box",
	"buling_box2",
	"buling_boat",
	"buling_plant",
	"buling_item",
	"buling_hulk",
	"buling_zaxiang",
	"buling_system",
	"buling_food",
	"buling_weapon",
	"buling_firerain",
	"buling_carrier",
	"buling_build",
	"buling_player",
	"buling_gun",
	--"buling_red",
	"seataro_planted",
}


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

    Asset( "IMAGE", "images/selectscreen_portraits/bulingbuling.tex" ),
    Asset( "ATLAS", "images/selectscreen_portraits/bulingbuling.xml" ),
	
	Asset( "IMAGE", "images/selectscreen_portraits/bulingbuling_silho.tex" ),
    Asset( "ATLAS", "images/selectscreen_portraits/bulingbuling_silho.xml" ),

    Asset( "IMAGE", "bigportraits/bulingbuling.tex" ),
    Asset( "ATLAS", "bigportraits/bulingbuling.xml" ),
	
	Asset( "IMAGE", "images/map_icons/bulingbuling.tex" ),
	Asset( "ATLAS", "images/map_icons/bulingbuling.xml" ),
	
	Asset( "ATLAS", "images/bulingui/buling_close.xml" ),
	Asset( "ATLAS", "images/bulingui/bulingui.xml" ),
	Asset( "ATLAS", "images/bulingui/buling_button.xml" ),
	Asset( "ATLAS", "images/bulingui/turnarrow_icon.xml" ),
	Asset( "ATLAS", "images/bulingui/buling_car_box.xml" ),
	Asset( "ATLAS", "images/bulingui/buling_rocky.xml" ),
	Asset( "ATLAS", "images/bulinggongye.xml" ),
	Asset( "ATLAS", "images/bulingyanjiu.xml" ),
	
	Asset("ANIM", "anim/generating_buling.zip"),
	Asset("ANIM", "anim/buling_player_basic.zip"),
	Asset("ANIM", "anim/buling_deerclops.zip"),
	
	--Asset("ANIM", "anim/altar_grate.zip"),
	
}

STRINGS.NAMES.BULINGBULING = "BulingBuling"
AddMinimapAtlas("images/map_icons/bulingbuling.xml")
AddModCharacter("bulingbuling","FEMALE")
modimport "scripts/string_bulingbuling.lua"
modimport "scripts/hamletislandconnector.lua"
modimport("scripts/buling_postinits/screens.lua")
modimport("scripts/buling_gengxin.lua")
local classpostinitfiles = {
	"loadgamescreen",
	"slotdetailsscreen",
}
for k, class in ipairs(classpostinitfiles) do
	local data = GLOBAL.require("buling_postinits/classes/"..class)
	if data.fullname and data.fn then
		AddClassPostConstruct(data.fullname, data.fn)
	end
end
--前往其他世界
AddGlobalClassPostConstruct("saveindex", "SaveIndex", function(self)
	function self:GoToDimension(dimname, x, y, z, save)
		self:SaveCurrent(function()
			--Records player data
			local playerdata = {}
			local player = GetPlayer()
			if player then
				if x or y or z then
					player.components.teleportonload:SetTarget(x,y,z)
				end
				playerdata = player:GetSaveRecord().data
				playerdata.leader = nil
				playerdata.sanitymonsterspawner = nil
			end
			local modename = dimname
			--Ensures dimension designations are present (modename is mostly redundant, but whatever)

			--Sets new mode
			self.data.slots[self.current_slot].current_mode = modename
			
			--Ensures mode data table is present
			if not self.data.slots[self.current_slot].modes[modename] then
				self.data.slots[self.current_slot].modes[modename] = {}
			end

			--Ensures mode data is present
			self.data.slots[self.current_slot].modes[modename].files = self.data.slots[self.current_slot].modes[modename].files or {}

			--Sets mode data
			self.data.slots[self.current_slot].modes[modename].world = 1
			
			--Generates save name
			local savename = self:GetSaveGameName(modename, self.current_slot)

			--Records player data to mode data
			--self.data.slots[self.current_slot].modes[modename].playerdata = playerdata
			local planet = ""
			--if modename == "stormplanet" then planet = "STORMPLANET" end
			local Levels = require("map/levels")
			for i,level in ipairs(Levels.custom_levels) do
				if level.id == modename  then
					self.data.slots[self.current_slot].modes[modename].playerdata = nil
					self.data.slots[self.current_slot].modes[modename].playerdata = playerdata
					self.data.slots[self.current_slot].modes[modename].options = {
						level_id = i
					}
					break
				end
			end
			--Clears mode data file name entry
			self.data.slots[self.current_slot].modes[modename].file = nil
			
			--Checks if save exists
			TheSim:CheckPersistentStringExists(savename, function(exists)
				if exists then
					--Records save name to mode data
					self.data.slots[self.current_slot].modes[modename].file = savename
				end
			end)

			--Save
			self:Save(function()
				SetPause(false)
				StartNextInstance({reset_action=RESET_ACTION.LOAD_SLOT, save_slot = SaveGameIndex:GetCurrentSaveSlot()}, true)
			end)
		end)
	end
end)
GLOBAL.SaveIndex.IsModeShipwrecked = function(self,slot) 
	return self:GetCurrentMode(slot) == "shipwrecked" or self:GetCurrentMode(slot) == "volcano" or self:GetCurrentMode(slot) == "stormplanet" or self:GetCurrentMode(slot) == "bossfight" 
end
GLOBAL.SaveIndex.IsModePorkland = function(self,slot) 
	return self:GetCurrentMode(slot) == "porkland" or self:GetCurrentMode(slot) == "edenplanet" 
end
--ui
local uilist= {
"buling_hechenglist_food",
"buling_hechenglist_plant",
"buling_hechenglist",
"buling_hechenglist_jixie",
"buling_system",
"buling_hechenglist_extraction",
"bulingnilui",
}
for k,v in pairs(uilist) do
	local bulingui = GLOBAL.require ("widgets/"..v)
	local function Addbulingui(self)
		controls = self
		if controls and GetPlayer().prefab == "bulingbuling" then 
			if controls.containerroot then
				controls.bulingui = controls.containerroot:AddChild(bulingui())
			end
		else
			return
		end
		controls.bulingui:Hide()
	end
	AddClassPostConstruct( "widgets/controls", Addbulingui )
end
local function Addbeerui(self)
	if self and self.item then
		if self.item.components.beerpower and self.item:HasTag("buling_lingjian") then
			self:SetPercent(self.item.components.beerpower:GetPercent())
		end
		self.inst:ListenForEvent("beerupdate",function(inst, data)
			self:SetPercent(data.percent)
        end, self.item)
	end
end
AddClassPostConstruct( "widgets/itemtile", Addbeerui )
--action
--查看终端
local BULING_STSTEM = GLOBAL.Action({},0,false,false,1)
BULING_STSTEM.id = "BULING_STSTEM"
BULING_STSTEM.str = STRINGS.BULING_STSTEM
BULING_STSTEM.fn = function(act) 
	print("就离谱")
	print(act)
	if act.doer then 
		GetPlayer():PushEvent("OpenBuling_system")
	end 
	return true	
end
AddAction(BULING_STSTEM)
AddStategraphActionHandler("wilson", ActionHandler(ACTIONS.BULING_STSTEM, "doshortaction"))
AddStategraphActionHandler("wilsonboating", ActionHandler(ACTIONS.BULING_STSTEM, "doshortaction"))
--抽取聚合酶
local BULING_ENZYME = GLOBAL.Action({mount_enabled=true})
BULING_ENZYME.id = "BULING_ENZYME"
BULING_ENZYME.str = STRINGS.BULING_ENZYME
BULING_ENZYME.fn = function(act) 
	if act.target.components.crop and act.target.components.crop.matured then
        if act.invobject and act.invobject.components.buling_getenzyme and act.doer and act.doer == GetPlayer() then
			act.invobject.components.finiteuses:Use(1)
			act.doer.components.inventory:GiveItem(SpawnPrefab("buling_juhemei_alpha"))
        end
    end
    return true
end
AddAction(BULING_ENZYME)
AddStategraphActionHandler("wilson", ActionHandler(ACTIONS.BULING_ENZYME, "dolongaction"))
AddStategraphActionHandler("wilsonboating", ActionHandler(ACTIONS.BULING_ENZYME, "dolongaction"))
--FangZhiCuSi
local DeathScreen = require "screens/deathscreen"
local function HandleDeathCleanup(wilson, data)
	local playtime = GetTimePlaying()
	playtime = math.floor(playtime*1000)
	SetTimingStat("time", "scenario", playtime)
	SendTrackingStats()
	local days_survived, start_xp, reward_xp, new_xp, capped = CalculatePlayerRewards(wilson)
	
	ProfileStatsSet("xp_gain", reward_xp)
	ProfileStatsSet("xp_total", new_xp)
	SubmitCompletedLevel() --close off the instance
	
	wilson.components.health.invincible = true
	
	wilson.profile:Save(function()
		SaveGameIndex:EraseCurrent(function() 
			scheduler:ExecuteInTime(3, function() 
				TheFrontEnd:PushScreen(DeathScreen(days_survived, start_xp, nil, capped))
			end)
		end)
	end)
end
local function OnPlayerDeath(wilson, data)
	local cause = data.cause or "unknown"
	local will_resurrect = wilson.components.resurrectable and wilson.components.resurrectable:CanResurrect(cause)
	local res = wilson.components.resurrectable:FindClosestResurrector(cause)
	wilson:DoTaskInTime(0,function()
		if SaveGameIndex:GetCurrentMode() == "stormplanet" or SaveGameIndex:GetCurrentMode() == "bossfight" or SaveGameIndex:GetCurrentMode() == "edenplanet" or SaveGameIndex:GetCurrentMode() == "desertplanet" then
			if will_resurrect or cause == "file_load" and res then
				print("正在复活")
			else
				HandleDeathCleanup(wilson, data)
			end
		end
	end)
end

AddPlayerPostInit(function(inst)
	inst:ListenForEvent( "death", function(b_inst, data) OnPlayerDeath(inst, data) end)
end)
