local Timer_h = Class(function (self, inst)
	self.inst = inst
	self.time = 10
	self.period = 1
	self.task = nil
	self.timerendfn = nil
	self.timertickfn = nil
	self.onendremove = false
end)

function Timer_h:OnSave()
    return {time = self.time, timerruning = self:IsRuning()}
end

function Timer_h:OnLoad(data)
	if data then
		self.time = data.time
		if data.timerruning then self:StartTimer() end
		print("timer load: "..self.time)
	end
end

function Timer_h:IsRuning()
	if self.task then return true
	else return false end
end

function Timer_h:SetTime(time)
	self.time = time
end

function Timer_h:StartTimer()
	if self.task == nil then
		self.task = self.inst:DoPeriodicTask(self.period,function ()
			self:OnTick()
	    end)
	end
end

function Timer_h:StopTimer()
	if self.task then
		self.task:Cancel()
		self.task = nil
	end
end

function Timer_h:OnTick()
	self.time = self.time - 1
	-- print(self.time..tostring(self:IsRuning()))
	if self.timertickfn then self.timertickfn(self.inst, self.time) end
    if self.time == 0 then 
    	self:StopTimer()
    	self.inst:PushEvent("Timer_h_End")
    	if self.timerendfn then self.timerendfn(self.inst, self.time) end
    	if self.onendremove then self.inst:RemoveComponent("timer_h") end
    end
    if self.time < 0 then
    	self.time = 0
    	-- self:StartTimer()
    	-- self:StopTimer()
    end
end

return Timer_h