local h=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\067\111\109\098\111")local Y=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\099\111\109\109\117\110\105\099\097\116\105\111\110")local q=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\104\101\114\111")local t=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\115\111\117\110\100")local I=require("\105\110\118\111\107\097\116\105\111\110\046\100\111\116\097\050\046\068\117\109\109\121\084\097\114\103\101\116")local x=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\070\114\101\101\115\116\121\108\101\067\111\109\098\111")local m=require("\105\110\118\111\107\097\116\105\111\110\046\076\111\103\103\101\114")local b=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\109\098\111\115\046\080\108\097\121\101\114\083\116\097\116\101\115")local M=require("\105\110\118\111\107\097\116\105\111\110\046\100\111\116\097\050\046\116\105\109\101\114\115")local N=require("\112\108\046\099\108\097\115\115")local p=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\110\115\116\046\097\098\105\108\105\116\121\095\108\105\115\116")local S=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\110\115\116\046\110\101\116\095\116\097\098\108\101")local R=N()local k="\099\111\109\098\111\115"local c="\067\111\109\098\111 \037\113 \110\111\116 \102\111\117\110\100"local s="\080\108\097\121\101\114 \037\100 \104\097\115 \110\111 \097\099\116\105\118\101 \099\111\109\098\111"local l="\067\111\109\098\111 \037\113 \099\097\110\'\116 \098\101 \102\105\110\105\115\104\101\100 \102\111\114 \112\108\097\121\101\114 \037\100"m.Extend(R)local function H()local h=require("\105\110\118\111\107\097\116\105\111\110\046\099\111\110\115\116\046\099\111\109\098\111\115")for h,Y in pairs(h)do Y.id=h for h,Y in pairs(Y.sequence)do Y.id=h end end return h end local function f(h)local Y=p[h.name]if Y==nil then return false end return not p[h.name]end local function y(h)return h and(not h.failed and not h.preFinished)end local function P(h)return h and(h.started and(not h.failed and not h.finished))end local function Q(h)return(h and h.id)==x.COMBO_ID end local function O()return GameRules:GetGameTime()end function R._init(q,h,Y)Y=Y or{}q.netTable=h q.state=b()if Y.logger then q.logger=Y.logger:Child(k)end q:load()end function R.load(h)h:d("\076\111\097\100\105\110\103")h.specs=H()h.netTable:Set(S.MAIN.KEYS.COMBOS,h.specs)end function R.Create(q,Y)if Y==x.COMBO_ID then return x({logger=q.logger})end local t=q.specs[Y]if t==nil then local h=c:format(Y)q:err(h)error(h)end return h(t,{logger=q.logger,clock=O})end function R.requireCombo(Y,h)local q=Y.state[h].combo if q==nil then local q=s:format(h:GetPlayerID())Y:err(q)error(q)end return q end function R.setup(x,h,Y)x.state[h].combo=Y q.setup(h,Y)local m=x.state[h].dummy if m==nil then m=I()x.state[h].dummy=m t.onDummyCreate(m)end m:Spawn()end function R.teardown(t,h,Y)Y=Y or{}t.state[h].combo=nil q.teardown(h,Y)local I=t.state[h].dummy if I~=nil then I:Kill()end end function R.start(I,h,q)I:setup(h,q)t.onComboStart(h)Y.sendStarted(h,q)end function R.stop(I,h,q)I:teardown(h,{hardReset=true})t.onComboStop(h)Y.sendStopped(h,q)end function R.OnAbilityUsed(t,h,Y,q)if f(q)then t:d("\079\110\065\098\105\108\105\116\121\085\115\101\100 \091\105\103\110\111\114\101\100\093",{player=h:GetPlayerID(),unit=Y.name,ability=q.name})return end t:d("\079\110\065\098\105\108\105\116\121\085\115\101\100",{player=h:GetPlayerID(),unit=Y.name,ability=q.name})t:CaptureAbility(h,q)t:Progress(h,q)end function R.OnEntityHurt(Y,h)local q=h:AttackerPlayerOwner()if q==nil then Y:d("\079\110\069\110\116\105\116\121\072\117\114\116 \091\105\103\110\111\114\101\100\093",{category=h.category;amount=h.amount})return end Y:d("\079\110\069\110\116\105\116\121\072\117\114\116",{category=h.category;amount=h.amount,victim=h:VictimName(),attacker=h:AttackerName();inflictor=h:InflictorName()})Y:ProgressDamage(q,h)end function R.OnItemPurchased(t,h,Y)local I=t.state[h].combo if not Q(I)then t:d("\079\110\073\116\101\109\080\117\114\099\104\097\115\101\100 \091\105\103\110\111\114\101\100\093",{player=h:GetPlayerID(),purchase=Y})return end t:d("\079\110\073\116\101\109\080\117\114\099\104\097\115\101\100",{player=h:GetPlayerID(),purchase=Y})q.refundPurchase(h,Y)end function R.Start(q,h,Y)q:d("\083\116\097\114\116",{player=h:GetPlayerID();id=Y.id})local t=q.state[h].combo if t~=nil and t.id~=Y.id then q:stop(h,t)else q:teardown(h,{hardReset=t==nil})end q:start(h,Y)end function R.Stop(Y,h)Y:d("\083\116\111\112",{player=h:GetPlayerID()})local q=Y:requireCombo(h)Y:stop(h,q)end function R.Restart(q,h,Y)q:d("\082\101\115\116\097\114\116",{player=h:GetPlayerID(),options=Y})local t=q:requireCombo(h)q:teardown(h,Y)t=q:Create(t.id)q:start(h,t)end function R.Progress(t,h,q)local I=t.state[h].combo if not y(I)then t:d("\080\114\111\103\114\101\115\115 \091\105\103\110\111\114\101\100\093",{player=h:GetPlayerID();ability=q.name})return end t:d("\080\114\111\103\114\101\115\115",{player=h:GetPlayerID();ability=q.name})if I:Progress(q)then if I.count==1 then Y.sendInProgress(h,I)end Y.sendProgress(h,I)if I:PreFinish()then t:PreFinish(h)end elseif not q:IsInvocationAbility()then t:Fail(h,q)end end function R.ProgressDamage(t,h,q)local I=t.state[h].combo if not P(I)then t:d("\080\114\111\103\114\101\115\115\068\097\109\097\103\101 \091\105\103\110\111\114\101\100\093",{player=h:GetPlayerID();category=q.category,amount=q.amount})return end t:d("\080\114\111\103\114\101\115\115\068\097\109\097\103\101",{player=h:GetPlayerID();category=q.category,amount=q.amount;victim=q:VictimName();attacker=q:AttackerName(),inflictor=q:InflictorName()})I:IncrementDamage(q.amount)Y.sendProgress(h,I)end function R.Fail(I,h,q)I:d("\070\097\105\108",{player=h:GetPlayerID()})local x=I:requireCombo(h)x:Fail()t.onComboStepError(h)Y.sendStepError(h,x,q)end function R.PreFinish(q,h)q:d("\080\114\101\070\105\110\105\115\104",{player=h:GetPlayerID()})local t=q:requireCombo(h)Y.sendPreFinish(h,t)M:Create({delay=t.waitDuration,callback=q.Finish,args={q;h}})end function R.Finish(q,h)q:d("\070\105\110\105\115\104",{player=h:GetPlayerID()})local I=q:requireCombo(h)if not I:Finish()then q:warnf(l,I.id,h:GetPlayerID())return end q:d("\070\105\110\105\115\104\101\100",{id=I.id;now=O()})t.onComboFinished(h)Y.sendFinished(h,I)end function R.StartCapturingAbilities(Y,h)Y:d("\083\116\097\114\116\067\097\112\116\117\114\105\110\103\065\098\105\108\105\116\105\101\115",{player=h:GetPlayerID()})Y.state[h].capturing=true end function R.StopCapturingAbilities(Y,h)Y:d("\083\116\111\112\067\097\112\116\117\114\105\110\103\065\098\105\108\105\116\105\101\115",{player=h:GetPlayerID()})Y.state[h].capturing=nil end function R.CaptureAbility(t,h,q)if t.state[h].capturing then Y.sendAbilityUsed(h,q)end end function R.FreestyleHeroLevelUp(t,h,Y)local I=t.state[h].combo if not Q(I)then t:d("\070\114\101\101\115\116\121\108\101\072\101\114\111\076\101\118\101\108\085\112 \091\105\103\110\111\114\101\100\093",{player=h:GetPlayerID(),options=Y})return end t:d("\070\114\101\101\115\116\121\108\101\072\101\114\111\076\101\118\101\108\085\112",{player=h:GetPlayerID(),options=Y})q.levelUp(h,Y)end return R
--- Combos manager.
-- @classmod invokation.combos.Combos
local Combo = require("invokation.combos.Combo")
local CombosComm = require("invokation.combos.communication")
local CombosHero = require("invokation.combos.hero")
local CombosSound = require("invokation.combos.sound")
local DummyTarget = require("invokation.dota2.DummyTarget")
local FreestyleCombo = require("invokation.combos.FreestyleCombo")
local Logger = require("invokation.Logger")
local PlayerStates = require("invokation.combos.PlayerStates")
local Timers = require("invokation.dota2.timers")
local class = require("pl.class")

local ABILITY_LIST = require("invokation.const.ability_list")
local NET_TABLE = require("invokation.const.net_table")

local M = class()

local LOGGER_PROGNAME = "combos"

local ERRF_COMBO_NOT_FOUND = "Combo %q not found"
local ERRF_COMBO_NOT_ACTIVE = "Player %d has no active combo"
local WARNF_COMBO_NOT_FINISHED = "Combo %q can't be finished for player %d"

Logger.Extend(M)

--- Purchase specification.
-- @table Purchase
-- @tfield string item Item name
-- @tfield number cost Purchase cost

--- Level up options specification.
--
-- If no options are given, levels hero up one level.
--
-- @table LevelUpOptions
-- @tfield[opt] int level Level up to specified level
-- @tfield[opt=false] bool maxLevel Level up to max level

local function loadSpecs()
  local specs = require("invokation.const.combos")

  for id, spec in pairs(specs) do
    spec.id = id

    for stepId, step in pairs(spec.sequence) do
      step.id = stepId
    end
  end

  return specs
end

local function isIgnoredAbility(ability)
  local switch = ABILITY_LIST[ability.name]

  if switch == nil then
    return false
  end

  return not ABILITY_LIST[ability.name]
end

local function isProgressingAbilities(combo)
  return combo and not combo.failed and not combo.preFinished
end

local function isProgressingDamage(combo)
  return combo and combo.started and not combo.failed and not combo.finished
end

local function isFreestyle(combo)
  return (combo and combo.id) == FreestyleCombo.COMBO_ID
end

local function gameTime()
  return GameRules:GetGameTime()
end

--- Constructor.
-- @tparam dota2.NetTable netTable NetTable instance
-- @tparam table options Options table
-- @tparam Logger options.logger Logger instance
function M:_init(netTable, options)
  options = options or {}

  self.netTable = netTable
  self.state = PlayerStates()

  if options.logger then
    self.logger = options.logger:Child(LOGGER_PROGNAME)
  end

  self:load()
end

function M:load()
  self:d("Loading")
  self.specs = loadSpecs()

  self.netTable:Set(NET_TABLE.MAIN.KEYS.COMBOS, self.specs)
end

function M:Create(id)
  if id == FreestyleCombo.COMBO_ID then
    return FreestyleCombo({ logger = self.logger })
  end

  local spec = self.specs[id]

  if spec == nil then
    local err = ERRF_COMBO_NOT_FOUND:format(id)

    self:err(err)
    error(err)
  end

  return Combo(spec, { logger = self.logger, clock = gameTime })
end

function M:requireCombo(player)
  local combo = self.state[player].combo

  if combo == nil then
    local err = ERRF_COMBO_NOT_ACTIVE:format(player:GetPlayerID())

    self:err(err)
    error(err)
  end

  return combo
end

function M:setup(player, combo)
  self.state[player].combo = combo

  CombosHero.setup(player, combo)

  local dummy = self.state[player].dummy

  if dummy == nil then
    dummy = DummyTarget()
    self.state[player].dummy = dummy

    CombosSound.onDummyCreate(dummy)
  end

  dummy:Spawn()
end

function M:teardown(player, options)
  options = options or {}

  self.state[player].combo = nil

  CombosHero.teardown(player, options)

  local dummy = self.state[player].dummy

  if dummy ~= nil then
    dummy:Kill()
  end
end

function M:start(player, combo)
  self:setup(player, combo)

  CombosSound.onComboStart(player)
  CombosComm.sendStarted(player, combo)
end

function M:stop(player, combo)
  self:teardown(player, { hardReset = true })

  CombosSound.onComboStop(player)
  CombosComm.sendStopped(player, combo)
end

--- Handles ability usage.
-- @tparam CDOTAPlayer player Player instance
-- @tparam dota2.Unit unit Unit instance
-- @tparam dota2.Ability ability Ability instance
function M:OnAbilityUsed(player, unit, ability)
  if isIgnoredAbility(ability) then
    self:d(
      "OnAbilityUsed [ignored]",
      { player = player:GetPlayerID(), unit = unit.name, ability = ability.name }
    )

    return
  end

  self:d(
    "OnAbilityUsed",
    { player = player:GetPlayerID(), unit = unit.name, ability = ability.name }
  )

  self:CaptureAbility(player, ability)
  self:Progress(player, ability)
end

--- Handles damage instances being dealt to entities.
-- @tparam dota2.DamageInstance damage DamageInstance instance
function M:OnEntityHurt(damage)
  local player = damage:AttackerPlayerOwner()

  if player == nil then
    self:d("OnEntityHurt [ignored]", { category = damage.category, amount = damage.amount })

    return
  end

  self:d("OnEntityHurt", {
    category = damage.category,
    amount = damage.amount,
    victim = damage:VictimName(),
    attacker = damage:AttackerName(),
    inflictor = damage:InflictorName(),
  })

  self:ProgressDamage(player, damage)
end

--- Handles item purchases.
-- @tparam CDOTAPlayer player Player instance
-- @tparam Purchase purchase Purchase information
function M:OnItemPurchased(player, purchase)
  local combo = self.state[player].combo

  if not isFreestyle(combo) then
    self:d("OnItemPurchased [ignored]", { player = player:GetPlayerID(), purchase = purchase })

    return
  end

  self:d("OnItemPurchased", { player = player:GetPlayerID(), purchase = purchase })

  CombosHero.refundPurchase(player, purchase)
end

--- Starts a combo for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam Combo combo Combo
function M:Start(player, combo)
  self:d("Start", { player = player:GetPlayerID(), id = combo.id })

  local current = self.state[player].combo

  if current ~= nil and current.id ~= combo.id then
    self:stop(player, current)
  else
    self:teardown(player, { hardReset = current == nil })
  end

  self:start(player, combo)
end

--- Stops currently active combo for the given player.
-- @tparam CDOTAPlayer player Player instance
function M:Stop(player)
  self:d("Stop", { player = player:GetPlayerID() })

  local combo = self:requireCombo(player)

  self:stop(player, combo)
end

--- Restarts a combo for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam table options Options table
-- @tparam[opt=false] bool options.hardReset Hard reset
function M:Restart(player, options)
  self:d("Restart", { player = player:GetPlayerID(), options = options })

  local combo = self:requireCombo(player)

  self:teardown(player, options)

  combo = self:Create(combo.id)

  self:start(player, combo)
end

--- Progresses the currently active combo for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam dota2.Ability ability Ability instance
function M:Progress(player, ability)
  local combo = self.state[player].combo

  if not isProgressingAbilities(combo) then
    self:d("Progress [ignored]", { player = player:GetPlayerID(), ability = ability.name })

    return
  end

  self:d("Progress", { player = player:GetPlayerID(), ability = ability.name })

  if combo:Progress(ability) then
    if combo.count == 1 then
      CombosComm.sendInProgress(player, combo)
    end

    CombosComm.sendProgress(player, combo)

    if combo:PreFinish() then
      self:PreFinish(player)
    end
  elseif not ability:IsInvocationAbility() then
    self:Fail(player, ability)
  end
end

--- Increments the damage amount of the currently active combo for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam dota2.DamageInstance damage DamageInstance instance
function M:ProgressDamage(player, damage)
  local combo = self.state[player].combo

  if not isProgressingDamage(combo) then
    self:d(
      "ProgressDamage [ignored]",
      { player = player:GetPlayerID(), category = damage.category, amount = damage.amount }
    )

    return
  end

  self:d("ProgressDamage", {
    player = player:GetPlayerID(),
    category = damage.category,
    amount = damage.amount,
    victim = damage:VictimName(),
    attacker = damage:AttackerName(),
    inflictor = damage:InflictorName(),
  })

  -- @fixme Only increment damage coming from currently active spells (including
  -- forged spirits) or autoattacks
  combo:IncrementDamage(damage.amount)
  CombosComm.sendProgress(player, combo)
end

--- Fails and stops currently active combo for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam dota2.Ability ability Ability instance
function M:Fail(player, ability)
  self:d("Fail", { player = player:GetPlayerID() })

  local combo = self:requireCombo(player)

  combo:Fail()

  CombosSound.onComboStepError(player)
  CombosComm.sendStepError(player, combo, ability)
end

--- Preemptively finishes a combo for the given player.
-- @tparam CDOTAPlayer player Player instance
function M:PreFinish(player)
  self:d("PreFinish", { player = player:GetPlayerID() })

  local combo = self:requireCombo(player)

  CombosComm.sendPreFinish(player, combo)

  Timers:Create({ delay = combo.waitDuration, callback = self.Finish, args = { self, player } })
end

--- Finishes a combo for the given player.
-- @tparam CDOTAPlayer player Player instance
function M:Finish(player)
  self:d("Finish", { player = player:GetPlayerID() })

  local combo = self:requireCombo(player)

  if not combo:Finish() then
    self:warnf(WARNF_COMBO_NOT_FINISHED, combo.id, player:GetPlayerID())
    return
  end

  self:d("Finished", { id = combo.id, now = gameTime() })

  CombosSound.onComboFinished(player)
  CombosComm.sendFinished(player, combo)
end

--- Starts capturing ability usage for the given player.
-- @tparam CDOTAPlayer player Player instance
function M:StartCapturingAbilities(player)
  self:d("StartCapturingAbilities", { player = player:GetPlayerID() })
  self.state[player].capturing = true
end

--- Stops capturing ability usage for the given player.
-- @tparam CDOTAPlayer player Player instance
function M:StopCapturingAbilities(player)
  self:d("StopCapturingAbilities", { player = player:GetPlayerID() })
  self.state[player].capturing = nil
end

--- Captures an instance of ability usage for the given player.
-- @tparam CDOTAPlayer player Player instance
-- @tparam dota2.Ability ability Ability instance
function M:CaptureAbility(player, ability)
  if self.state[player].capturing then
    CombosComm.sendAbilityUsed(player, ability)
  end
end

--- Handles freestyle hero level up.
-- @tparam CDOTAPlayer player Player instance
-- @tparam LevelUpOptions options
function M:FreestyleHeroLevelUp(player, options)
  local combo = self.state[player].combo

  if not isFreestyle(combo) then
    self:d("FreestyleHeroLevelUp [ignored]", { player = player:GetPlayerID(), options = options })
    return
  end

  self:d("FreestyleHeroLevelUp", { player = player:GetPlayerID(), options = options })

  CombosHero.levelUp(player, options)
end

return M
