
QuickClickBlocker = public()
local SavableConfig = SavableTable("savable_config")

local MaxClickCount  = tonumber( Config["ho_max_click_count"] )
local MinClickTime   = tonumber( Config["ho_min_click_time"]  )
local MaxPunishment  = tonumber( Config["ho_stop_click_time"] )
local PunishmentCursor        = Config["ho_punish_cursor_name"]

if PunishmentCursor == ""  then PunishmentCursor = "cur_wait" end
if MaxClickCount    == nil then MaxClickCount = 5 end
if MinClickTime     == nil then MinClickTime  = 5 end
if MaxPunishment    == nil then MaxPunishment = 5 end


function QuickClickBlocker:Create()
  self:Init()
  self.Run            = false
end

function QuickClickBlocker:Init()
  self.List           = {}
  
  self.MaxClickCount  = MaxClickCount
  self.MinClickTime   = MinClickTime
  self.MaxPunishment  = MaxPunishment  
  
  self.Begin          = 1
  self.End            = 1
  self.Current        = 1
  self.Punishment     = false
  self.LastTime       = 0
end

function QuickClickBlocker:Start()
  self:Init()
  self.Run = true
end

function QuickClickBlocker:Stop()
  self.Run = false
end

function QuickClickBlocker:CanClick()
  if not self.Run then
    return true
  end  
  return  not self.Punishment
end

function QuickClickBlocker:Update()
  if not self.Punishment then
    return 
  end

  Particle:SetPosition(states["ho_punish_particle_name"], Ogre.Vector2(0.1,0.1), 1200)
  
  t = Time:GetTime_second()
  if  t < self.LastTime + self.MaxPunishment then
    return false
  end
  self:StopPunishment()
end

function QuickClickBlocker:StartPunishment()
  if states["sys_first_click_punish"] == 0 then
    ShowGameHint("game_hint_8")
    states["sys_first_click_punish"]  = 1
  end 
  PlaySound("snd_fx_anty_quick_click")
  self.Punishment = true
  self.LastTime = Time:GetTime_second()
  Particle:Add(states["ho_punish_particle_name"])
  Cursors:SetDefaultCursor("cur_wait")
  states["sys_block_esc"] = 1
  self:Update()
end

function QuickClickBlocker:StopPunishment()
  states["sys_block_esc"] = 0
  self:Init()
  self.Punishment = false
  Cursors:Reset()
  Particle:Remove(states["ho_punish_particle_name"], nil)
end

function QuickClickBlocker:AddClick()
  
  if not self.Run  then
    return true
  end
  local t = Time:GetTime_second()
  
  if self.Punishment  then
    return false
  end
  
  local lastT = self.List[self.Begin]  
  self.List[self.Current] = t
  
  if self.Current == self:DecIterator(self.Begin)  then
    self.Begin = self:IncIterator( self.Begin )
    if t - lastT < self.MinClickTime then
      self:StartPunishment()
    end
  end
  
  self.Current = self:IncIterator(self.Current)
  return true
end

function QuickClickBlocker:IncIterator(iterator)
  if iterator < self.MaxClickCount then
    return iterator + 1
  end
  return 1
end

function QuickClickBlocker:DecIterator(iterator)
  if iterator > 1 then
    return iterator - 1
  end
  return self.MaxClickCount
end

