--[[
File: lwc_food.script
Copyright: © Real Wolf, Ирбис
Author: Real Wolf
]]

function init(obj)
	local new_binder = food_binder(obj)
	obj:bind_object(new_binder)
end

class "food_binder" (object_binder)
function food_binder:__init(obj) super(obj)
	self.initialized = false
	self.loaded = false
	self.cond = 1
	self.next_update = 0
end 

function food_binder:reload(section)
	object_binder.reload(self, section)
end

function food_binder:reinit()
	object_binder.reinit(self)
end

function food_binder:net_save_relevant()
	return true
end

function food_binder:save(packet)
	object_binder.save(self, packet)
	packet:w_u8( math.floor(self.object:condition() * 100) )
end

function food_binder:load(reader)
	object_binder.load(self, reader)
	self.loaded = true
	if not reader:r_eof() then
		self.cond = math.floor( reader:r_u8() ) / 100
	end
end

function food_binder:net_spawn(data)
	if not object_binder.net_spawn(self, data) then
		return false
	end
	return true
end

function food_binder:net_destroy()
	object_binder.net_destroy(self)
end

function food_binder:update(delta)
	object_binder.update(self, delta)
	if not ( db.actor or db.actor:alive() ) then return end
	if self.object:section() == "separator" then return end

	--' Устанавливаем состояния еды, т.к. оно сбивается при загрузке
	if self.loaded == true then
		self.loaded = false
		self.object:set_condition(self.cond)
	end

	if lwc_ui_slot_upgrade.read_if_exist(system_ini(), self.object:section(), "cor_time", false) then
		if self.next_update <= time_global() then
			self.object:set_condition(self.object:condition() - self:GetDamage())
			if self.object:parent() ~= nil then
				local npc = level.object_by_id( self.object:parent():id() )
				if self.object:condition() < 0.1 or npc.radiation > 0.6 then
					amk.spawn_item_in_inv(self.object:section().."_fake", npc)
					local sobj = alife():object( self.object:id() )
					if IsStalker(npc) then
						npc:drop_item(sobj)
					end
					alife():release(sobj)
				end	
			end

			self.next_update = time_global() + (( 60 / ( lwc.timefactor() + 3 ) ) * 1000)
		end
	end		
end

function food_binder:GetDamage()
	local iDay = lwc_ui_slot_upgrade.read_if_exist(system_ini(), self.object:section(), "cor_time", false)
	if iDay then
		return 100/iDay/24/100/60
	end   
end