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

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

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

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

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

function accum_binder:net_save_relevant()
	return true
end

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

function accum_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 accum_binder:net_spawn(data)
	if not object_binder.net_spawn(self, data) then
		return false
	end
	return true
end

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

function accum_binder:update(delta)
	object_binder.update(self, delta)
	if not ( db.actor or db.actor:alive() ) then return end

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

	local active_item = db.actor:active_item()
	if active_item then
		--' На секцию можно не проверять, т.к. биндер будет только у детекторов, но мало ли.
		if string.find(active_item:section(),"bolt_d") and self.object:id() == active_item:id() then
			if self.next_update <= time_global() then
				if self.object:condition() > 0.1 then
					lwc_detector.max_dist = lwc_detector.start_dist*self.object:condition()
					lwc_detector.screen_max_dist = lwc_detector.screen_start_dist*self.object:condition()
					self.object:set_condition(self.object:condition() - self.corrupt)
				end

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

function accum_binder:use_accum()
	local slot = db.actor:item_in_slot(5)
	if slot then
		if string.find(slot:section(),"bolt_d") then
			if slot:condition() < 1 then
				slot:set_condition(1)
				news_manager.send_tip(db.actor, "Аккумулятор детектора заменён.", nil, nil, 5000)
			else
				news_manager.send_tip(db.actor, "Аккумулятор детектора не разряжён.", nil, nil, 5000)
				amk.spawn_item_in_inv("det_accum")
			end								
		else
			news_manager.send_tip(db.actor, "В слоте нет детектора.", nil, nil, 5000)
			amk.spawn_item_in_inv("det_accum")
		end
	else
		news_manager.send_tip(db.actor, "В слоте нет детектора.", nil, nil, 5000)
		amk.spawn_item_in_inv("det_accum")
	end
end