WoWInterface SVN EERaidAdmin

[/] [EELoot.lua] - Rev 3

Compare with Previous | Blame | View Log

EELoot = EERaidAdmin:NewModule("EELoot", "AceConsole-3.0", "AceBucket-3.0", "AceEvent-3.0", "AceComm-3.0")

------ VARIABLES
---- GLOBALS
local db --= EERaidAdmin.db
local __IsDebugging = 0
local __raidActiveGroups = EERaidAdmin.__raidActiveGroups
local __raidActivePlayers = EERaidAdmin.__raidActivePlayers
local ServerDateTime = EERaidAdmin.ServerDateTime
--EELoot.db = db.global
---- LOCALS
local __UpdateRate = 0.1
local _WinnerRoll = 0
local _WinnerNames = {}
local bars = {}
local playerToBarIndex = {}
local raidPlayers = {}
local SelectedLoot = 1
local SelectedPlayer = nil
local _LootMode

local GP = LibStub("LibGearPoints-1.0");

-- Name cannot be the same as the object name, otherwise cannot be properly hooked :/
local RollLootTooltip = CreateFrame( "GameTooltip", "EELootGameTooltip", UIParent, "GameTooltipTemplate" ) 

------ HELPER FUNCTIONS
local function _debug(msg, fatal)
  if __IsDebugging == 1 or fatal then
    EELoot:Print("|cffdd0000debug: "..msg.."|r")
  end
end

local function _color(r, g, b, msg)
  if type(r) == "table" then
    if r.r then r, g, b = r.r, r.g, r.b else r, g, b = unpack(r) end
  end
  t_color = string.format("|cff%02x%02x%02x", r*255, g*255, b*255)
  if msg ~= '' then
    return t_color..msg..'|r'
  else
    return t_color
  end
end

local function _message(msg, label)
  local output = ""
  output = _color(0,1,1, 'EELoot: ')
  if label then
    output = output.._color(0,0.7,0.7, label..': ')
  end
  output = output..msg
  print(output)  
end

local function _getItemId(itemlink)
  local prestring = string.gsub(itemlink, ".-\124H([^\124]*)\124h.*", "%1")
  local _,itemid,_,_,_,_,_,_,_ = strsplit(":", prestring)
  return itemid
end

local function _sortEligiblePlayers(a, b)
  if (not a) then
    return false
  elseif (not b) then
    return true
  else
    return (a.points > b.points)
  end   
end

local function _sortRaidSubgroupAsc(a, b)
  if (not a) then
    return false
  elseif (not b) then
    return true
  else
    return (a.subgroup < b.subgroup)
  end   
end

local function _adjustColorToIndex(index, r, g, b)
  local r, g, b = r, g, b
  if mod(index, 2) == 0 then
    --
  else
    r = r+0.03 > 1 and r-0.03 or r+0.03
    g = g+0.03 > 1 and g-0.03 or g+0.03
    b = b+0.03 > 1 and b-0.03 or b+0.03    
  end
  return r, g, b
end

local function __________()
  -- ignore, IDE cheat
end

function EELoot:LOOT_OPENED()
  _debug("LOOT_OPENED")
  -- TODO: hotfix, otkryvaetsja toka v rejde, i toka MLom
  -- lootmethod, masterlooterPartyID, masterlooterRaidID = GetLootMethod();
  -- if not(lootmethod == "master" and masterlooterPartyID == 0) then
  --    return;
  -- end 
  if UnitInRaid("player") then
    -- FIXME: bruteforcing
    -- if revisiting, then skipping the checks
    for i = 1, GetNumLootItems() do    
      if db.CollectedLoot[1] then -- esli sushestvuet pervyj podobranyj predmet...
        if LootSlotIsItem(i) then
          if db.CollectedLoot[1].itemLink == GetLootSlotLink(i) then -- FIXME: ...sravnivaem etot predmet s pervym iz podobranogo
            self:CollectLoot()
            EERaidAdmin.Anchor:Show()
            EERaidAdmin:SetTab(3)
            return
          end
        end
      end
    end
    
    -- Автосбор зеленки
    if db.__AutoGreen == true then
      for i = 1, GetNumLootItems() do
        if LootSlotIsItem(i) then
          _, _, itemRarity, _, _, _, _, _, _, _ = GetItemInfo(GetLootSlotLink(i))
          if itemRarity == 2 then
            -- najdena zelenka
            for ci = 1, GetNumRaidMembers() do
              -- otdaem sebe
              if (GetMasterLootCandidate(ci) == UnitName("player")) then
                _debug("Пытаюсь подобрать зеленку",1)
                GiveMasterLoot(i, ci)                
              end
            end
          end
        end
      end
    end
    
    -- else trying against ML threshold
    for i = 1, GetNumLootItems() do
      if LootSlotIsItem(i) then
        _, _, itemRarity, _, _, _, _, _, _, _ = GetItemInfo(GetLootSlotLink(i))
        if itemRarity >= GetLootThreshold() and itemRarity ~= 2 then
        -- if itemRarity >= 0 then
          _debug("> rarity threshold met -- picking")
          self:CollectLoot()
          if db.__AutoAnnounceLoot == true then
            if (GetNumRaidMembers() > 20) then -- check if raid is large
              lootmethod, masterlooterPartyID, _ = GetLootMethod(); -- check if ML
              if (lootmethod == "master" and masterlooterPartyID == 0) then
                self:LootAnnounceGuild(); -- announce to guild
              end 
            end
          end
                  self:LootAnnounceRaid();
          EERaidAdmin.Anchor:Show()
          EERaidAdmin:SetTab(3)
          return
        end
      end
    end
  end
end

function EELoot:LOOT_CLOSED()
  _debug("LOOT_CLOSED")
  self:OfflineMode()  
end

function EELoot:LOOT_SLOT_CLEARED()  
  _debug("LOOT_SLOT_CLEARED")
  if _LootMode == 1 then     
    self:CollectLoot()
    self:CalculateWinner()
    self:DrawInterestAll()  
  end
end


function EELoot:PLAYER_TARGET_CHANGED()
  -- if UnitExists("target") and UnitIsPlayer("target") then
  --   local _, class = UnitClass("target")
  --   self.GiveLoot:SetText("Отдать ".._hex(RAID_CLASS_COLORS[class])..UnitName("target").."|r")
  --   self.GiveLoot:Enable()
  -- else
  --   self.GiveLoot:SetText("Отдать |cffdd0000"..UnitName("target").."|r")
  --   self.GiveLoot:Disable()
  -- end
  -- local size = self.GiveLoot:GetTextWidth()+30
  -- if size < 80 then
  --   size = 80
  -- end
  --   
  -- self.GiveLoot:SetWidth(size)
end

function EELoot:RAID_ROSTER_UPDATE()
  _debug("RAID_ROSTER_UPDATE")
  if self.Anchor:IsVisible() then
    _debug("> anchor visible: updating")
    self:UpdateRaidPlayerInfo()
    self:DrawPlayerBars()
    self:CalculateWinner()
    self:DrawInterestAll()
  end
end

function EELoot:CHAT_MSG_SYSTEM()
  _debug("CHAT_MSG_SYSTEM")
  -- FIXME: move it down the ladder later
  if not db.CollectedLoot[SelectedLoot] then return end -- nothing to roll for
  if string.find(arg1, "выбрасывает") and string.find(arg1, "%(1%-100%)") then
    local _, _, name, roll = string.find(arg1, "(.+) выбрасывает (%d+)") -- TODO: any delocalized way to do this?    
    self:CalculateRoll(name, roll)    
  end
end

function EELoot:CHAT_MSG_SYSTEM_SLOW()
  _debug("CHAT_MSG_SYSTEM_SLOW")  
  self:CalculateWinner()
  self:DrawInterestAll()
end

local function __________()
  -- ignore, IDE cheat
end

function EELoot:SendStartRoll()  
  _debug("SendStartRoll")
  local t_eligible_players = self:GetEligiblePlayers()
  if #t_eligible_players > 0 then               -- fixme remove roll for one person
  --if #t_eligible_players == 1 then            -- fixme remove roll for one person
  --  wipe(_WinnerNames)
  --  _WinnerRoll = 0
  -- db.CollectedLoot[SelectedLoot].interest[t_eligible_players[0]].roll = 0
  -- elif #t_eligible_players > 1 then
    wipe(_WinnerNames)
    _WinnerRoll = 0
    for i, name in ipairs(t_eligible_players) do
      db.CollectedLoot[SelectedLoot].interest[name].roll = 0
      EELoot:SendCommMessage("LSRA", "START_ROLL", "WHISPER", name)
    end
  end
end

function EELoot:SendPollEquip(player)
  _debug("SendPollEquip")
  if not db.CollectedLoot[SelectedLoot] then return end
  local item = db.CollectedLoot[SelectedLoot].itemLink
  if not IsEquippableItem(item) then return end  
  if player then
    _debug("> whisper")
    self:SendCommMessage("LSRA", "POLL_EQUIP;"..item, "WHISPER", player)
  else
    _debug("> raid")
    self:SendCommMessage("LSRA", "POLL_EQUIP;"..item, "RAID")
  end
end

function EELoot:SendRePoll(player)
  _debug("SendRePoll")
  if not db.CollectedLoot[SelectedLoot] then return end
  if not db.CollectedLoot[SelectedLoot].rolltype then return end
  self:DeleteInterest(player)
  wipe(_WinnerNames)
  _WinnerRoll = 0
  self:DrawInterestAll()
  if db.CollectedLoot[SelectedLoot].rolltype == "STANDARD" then
    self:SendCommMessage("LSRA", "POLL_STANDARD;"..db.CollectedLoot[SelectedLoot].itemLink, "WHISPER", player)
  elseif db.CollectedLoot[SelectedLoot].rolltype == "QUICK" then
    self:SendCommMessage("LSRA", "POLL_QUICK;"..db.CollectedLoot[SelectedLoot].itemLink, "WHISPER", player)
  end  
end

function EELoot:SendStandardRoll()
  _debug("SendStandardRoll")  
  local item = db.CollectedLoot[SelectedLoot].itemLink
  self:DeleteInterest()
  self:ClearInterest()
  db.CollectedLoot[SelectedLoot].rolltype = "STANDARD"  
  self:DrawInterestAll()  
  self:SendPollEquip()
  self:SendCommMessage("LSRA", "POLL_STANDARD;"..item, "RAID") -- TODO:
end

function EELoot:SendQuickRoll()  
  _debug("SendQuickRoll")
  local item = db.CollectedLoot[SelectedLoot].itemLink
  self:DeleteInterest()
  self:ClearInterest()
  db.CollectedLoot[SelectedLoot].rolltype = "QUICK"  
  self:DrawInterestAll()
  self:SendPollEquip()
  self:SendCommMessage("LSRA", "POLL_QUICK;"..item, "RAID") -- TODO:
end

local function __________()
  -- ignore, IDE cheat
end

function EELoot:GetItemStatus(itemlink)
  _debug("GetItemStatus "..itemlink, 1)
  -- experemental tooltip parser
  local ScanTooltip = CreateFrame("GameTooltip", "ScanTooltip", UIParent, "GameTooltipTemplate")
  ScanTooltip:SetOwner(UIParent, "ANCHOR_NONE")
  ScanTooltip:ClearLines()
  ScanTooltip:SetHyperlink(itemlink)
  -- _debug(ScanTooltip:NumLines(), 1)
  if ScanTooltip:NumLines() > 3 then
    local bindstatus = getglobal("ScanTooltipTextLeft2"):GetText()
    local asd = getglobal("ScanTooltipTextRight2"):GetText()
    local asdf = getglobal("ScanTooltipTextLeft3"):GetText()
    local asdfg = getglobal("ScanTooltipTextRight3"):GetText()
    local r, g, b, a = getglobal("ScanTooltipTextRight2"):GetTextColor()
    print(bindstatus)
    print(asd)
    print(asdf)
    print(asdfg)
    print(r.." "..g.." "..b.." "..a)
  end
  ScanTooltip:Hide()  
end

function EELoot:TestStatus()
  self:GetItemStatus(GetInventoryItemLink("player",1))
  self:GetItemStatus(GetContainerItemLink(0, 1))  
end

function EELoot:UpdateRaidPlayerInfo()
  _debug("UpdateRaidPlayerInfo")
  -- wipe old tables
  wipe(raidPlayers)
  wipe(playerToBarIndex)  
  for i = 1, GetNumRaidMembers(), 1 do
    local name, _, subgroup, _, _, class, _, online, _, _, _ = GetRaidRosterInfo(i)
    raidPlayers[i] = { name=name, class=class, subgroup=subgroup, online = online }
  end
  -- sort, according to the subgroup number (1,2..)
  table.sort(raidPlayers, _sortRaidSubgroupAsc)
  -- fill the playerToBarIndex lookup table
  for i, v in pairs(raidPlayers) do 
    playerToBarIndex[v.name] = i    
  end
end

function EELoot:DrawPlayerBars()
  _debug("DrawPlayerBars")
  -- Hide all bars
  for i = 0, #bars do
    bars[i]:Hide()
  end
  -- clean them out
  wipe(bars)
  -- recreate the bars from scratch
  for i = 1, #raidPlayers, 1 do    
    local name, class, subgroup, online = raidPlayers[i].name, raidPlayers[i].class, raidPlayers[i].subgroup, raidPlayers[i].online
    if subgroup <= 5 then -- TODO: strogo 5 pervyh grupp?
      -- set player name and class color, paint gray if user is offline
      bars[i].PlayerNameText:SetText(name)
      bars[i].player = name
      bars[i].class = class
      if online then
        bars[i].PlayerNameText:SetTextColor(RAID_CLASS_COLORS[class].r, RAID_CLASS_COLORS[class].g, RAID_CLASS_COLORS[class].b, 1)
      else
        bars[i].PlayerNameText:SetTextColor(0.4, 0.4,0.4)
      end
      
      bars[i].Karma:SetText('|cffe6cc80'..EEKarma:KarmaGetTotal(name)..'|r')
      -- show the bar
      bars[i].ItemText:Hide()
      bars[i]:Show()
    end
    -- limit the number of bars
    if i == __raidActivePlayers then break end
  end
end

function EELoot:SelectPlayer(bar_id)
  _debug("SelectPlayer")
  if not db.CollectedLoot[SelectedLoot] then return end  
  
  if db.CollectedLoot[SelectedLoot].winner then
    -- TODO: esli pobeditel' uzhe ustanovlen, sootvetstvenno zabrana karma, 
    --       to s vydelennym chelovekom bol'she nichego podelat' nel'zja, tak li eto?    
  else
    self:DrawInterestAll()  
    -- highlight the bar
    SelectedPlayer = bar_id
    local i_r, i_g, i_b = _adjustColorToIndex(bar_id, 0.50, 0.50, 0)
    bars[bar_id].texture:SetTexture(i_r,i_g,i_b,0.95)
    bars[bar_id]:SetBackdropColor(0,0,0,0)

    -- set "declare winner" button and its "deduct karma" window
    self.WinnerButton:SetText("Выиграл ".._color(RAID_CLASS_COLORS[bars[bar_id].class], nil, nil, bars[bar_id].player))
    local size = self.WinnerButton:GetTextWidth()+30
    if size < 80 then size = 80; end
    self.WinnerButton:SetWidth(size)
    self.WinnerButton:Enable();
    self.DeductKarma:SetText(self:GetKarmaCost(bars[bar_id].player))
    
    -- give loot button    
    -- self.GiveLootButton:SetText("Выдать ".._color(RAID_CLASS_COLORS[bars[bar_id].class], nil, nil, bars[bar_id].player))
    -- local size = self.GiveLootButton:GetTextWidth()+30
    -- if size < 80 then size = 80; end
    -- self.GiveLootButton:SetWidth(size)    
    -- if _LootMode == 1 then self.GiveLootButton:Enable() end
    
  end
end

function EELoot:DenyPlayer(bar_id)
  _debug("DenyPlayer")
  if db.CollectedLoot[SelectedLoot] then
    _debug(">")
    if db.CollectedLoot[SelectedLoot].interest then
      _debug(">>")
      if db.CollectedLoot[SelectedLoot].interest[bars[bar_id].player] then
        _debug(">>>")
        self:DeleteInterest(bars[bar_id].player)
        db.CollectedLoot[SelectedLoot].interest[bars[bar_id].player].interest = "PASS"
        self:CalculateWinner()
        self:DrawInterestAll()
      end
    end
  end
end

local function ______bars()
  --vvvvvvvvvvvvvvvvvvv
end

setmetatable(bars, {__index = function(self, bar_id)    
  -- refactor local options
  local inset = 20
  local height = 20
  local fontsize = 13  
  local bar = CreateFrame("Button", nil, EELoot.BarList)  
  
  self[bar_id] = bar
  
  bar.player = nil
  bar.class = nil
  
  --bar:SetWidth(EELoot.BarList:GetWidth())  
  bar:SetHeight(height)  
  bar:EnableMouse(true)
  bar:SetFrameStrata("HIGH")
  bar:RegisterForClicks("LeftButtonUp", "RightButtonUp")
  bar:SetHighlightTexture( "Interface\\QuestFrame\\UI-QuestTitleHighlight")
  bar:SetPoint("TOPLEFT", EELoot.BarList, "TOPLEFT", 0, -((bar_id-1) * height) )
  bar:SetPoint("TOPRIGHT", EELoot.BarList, "TOPRIGHT", 0, -((bar_id-1) * height) )
  
  -- paint the bar with solid texture, and a striped backdrop for alternate effect
  bar.texture = bar:CreateTexture()  
  bar.texture:SetAllPoints(bar)  
  local i_r, i_g, i_b = _adjustColorToIndex(bar_id, 0.25, 0.25, 0.25)
  bar.texture:SetTexture(i_r, i_g, i_b, 0.5)
  bar:SetBackdrop( {bgFile = "Interface\\Addons\\EERaidAdmin\\textures\\Stripes", edgeFile = nil, tile = true, tileSize = 32, edgeSize = nil, insets = { left = 0, right = 0, top = 0, bottom = 0 }});  
  bar:SetBackdropColor(i_r, i_g, i_b, 0.0)
  bar:SetScript("OnClick", function(self, button)
    if button == "LeftButton" then
      EELoot:SelectPlayer(bar_id)
    elseif button == "RightButton" then      
      EELoot:DenyPlayer(bar_id)
    end
  end)
  
  bar.PlayerNameText = bar:CreateFontString(nil, nil, "GameFontNormalSmall")
  bar.PlayerNameText:SetFont("Fonts\\FRIZQT__.TTF", fontsize)  
  bar.PlayerNameText:SetJustifyH("LEFT")
  bar.PlayerNameText:SetWidth(80)
  bar.PlayerNameText:SetHeight(fontsize)
  bar.PlayerNameText:SetNonSpaceWrap(false)  
  bar.PlayerNameText:SetPoint("LEFT", bar, "LEFT", 10, 0) 

  bar.ItemText = CreateFrame("Button", nil, bar)
  
  local t_f_s1 = bar.ItemText:CreateFontString(nil, nil, "GameFontNormalSmall")
  t_f_s1:SetFont("Fonts\\FRIZQT__.TTF", fontsize-1)  
  t_f_s1:SetJustifyH("LEFT")
  t_f_s1:SetPoint("LEFT")  
  t_f_s1:SetWidth(300)
  t_f_s1:SetNonSpaceWrap(false)
  
  bar.ItemText:SetFontString(t_f_s1) 
  bar.ItemText:EnableMouse(true)
  bar.ItemText:SetWidth(300)
  bar.ItemText:SetHeight(height)
  bar.ItemText:SetPoint("LEFT", bar.PlayerNameText, "RIGHT", 5, 0)
  bar.ItemText:SetScript("OnClick", function() 
    EELoot:SendPollEquip(bar.PlayerNameText:GetText())
  end )  
  bar.ItemText:SetScript("OnEnter", function()
    if bar.ItemText:GetText() then
      if GetItemInfo(bar.ItemText:GetText()) then
        RollLootTooltip:SetOwner(bar.ItemText, "ANCHOR_BOTTOMRIGHT", -(bar.ItemText:GetWidth()+5), 0) 
        RollLootTooltip:ClearAllPoints();      
        RollLootTooltip:SetHyperlink(bar.ItemText:GetText())   
        RollLootTooltip:Show()
      end
    end
  end)
  bar.ItemText:SetScript("OnLeave", function()
    RollLootTooltip:Hide();
  end)
  bar.ItemText:Hide()
  
  bar.Total = bar:CreateFontString(nil, nil, "GameFontNormalSmall")
  bar.Total:SetFont("Fonts\\FRIZQT__.TTF", fontsize)
  bar.Total:SetJustifyH("LEFT")
  bar.Total:SetWidth(35) -- TODO:
  bar.Total:SetHeight(fontsize) -- TODO:
  bar.Total:SetNonSpaceWrap(false)
  bar.Total:SetPoint("RIGHT", bar, "RIGHT")
  
  bar.Roll = bar:CreateFontString(nil, nil, "GameFontNormalSmall")
  bar.Roll:SetFont("Fonts\\FRIZQT__.TTF", fontsize)
  bar.Roll:SetJustifyH("LEFT")
  bar.Roll:SetWidth(35)
  bar.Roll:SetHeight(fontsize)
  bar.Roll:SetNonSpaceWrap(false)  
  bar.Roll:SetPoint("RIGHT", bar.Total, "LEFT", -10, 0)
  
  bar.Karma = bar:CreateFontString(nil, nil, "GameFontNormalSmall")
  bar.Karma:SetFont("Fonts\\FRIZQT__.TTF", fontsize)
  bar.Karma:SetJustifyH("RIGHT")
  bar.Karma:SetWidth(35)
  bar.Karma:SetHeight(fontsize)
  bar.Karma:SetNonSpaceWrap(false)  
  bar.Karma:SetPoint("RIGHT", bar.Roll, "LEFT", -5, 0)
  
  bar.InterestPane = CreateFrame("Frame",nil,bar)  
  --bar.InterestPane:EnableMouse(true)
  bar.InterestPane:SetFrameStrata("DIALOG")
  bar.InterestPane:SetWidth(30)
  bar.InterestPane:SetHeight(height)
  bar.InterestPane:SetPoint("RIGHT", bar.Karma, "LEFT", 0, 0) 
  
  -- paint the bar with solid texture, and a striped backdrop for alternate effect
  bar.InterestPane.texture = bar.InterestPane:CreateTexture()  
  --bar.InterestPane.texture:SetDrawLayer("OVERLAY")
  bar.InterestPane.texture:SetPoint("CENTER")
  bar.InterestPane.texture:SetAllPoints(bar.InterestPane)    
  bar.texture:SetTexture(0, 0, 0, 0)    
  bar.InterestPane:SetBackdrop( {bgFile = "Interface\\Addons\\EERaidAdmin\\textures\\Stripes", edgeFile = nil, tile = true, tileSize = 32, edgeSize = nil, insets = { left = 0, right = 0, top = 0, bottom = 0 }});  
  bar.InterestPane:SetBackdropColor(0, 0, 0, 0)

  bar.InterestButton = CreateFrame("Button", nil, bar.InterestPane)
  local t_f_s2 = bar.InterestButton:CreateFontString(nil, nil, "GameFontNormalSmall")
  t_f_s2:SetFont("Fonts\\FRIZQT__.TTF", fontsize+2)  
  t_f_s2:SetJustifyH("CENTER")
  t_f_s2:SetPoint("CENTER")  
  bar.InterestButton:SetFontString(t_f_s2)
  bar.InterestButton:EnableMouse(true)
  bar.InterestButton:SetHeight(16)
  bar.InterestButton:SetWidth(16)  
  bar.InterestButton:SetScript("OnClick", function() EELoot:SendRePoll(bar.player) end )  
  bar.InterestButton:SetPoint("CENTER", bar.InterestPane, 0, 0)

  return bar
  
end})



function EELoot:GetKarmaCost(player)
  _debug("GetKarmaCost")
  if not db.CollectedLoot[SelectedLoot] then return 0 end
  if not db.CollectedLoot[SelectedLoot].interest then return 0 end
  if not db.CollectedLoot[SelectedLoot].interest[player] then return 0 end
  if not db.CollectedLoot[SelectedLoot].interest[player].interest then return 0 end
  if db.CollectedLoot[SelectedLoot].interest[player].interest == "NEEDMAIN" or db.CollectedLoot[SelectedLoot].interest[player].interest == "NEEDOFF" then    
  --  return floor(EEKarma:KarmaGetTotal(player)/2);
      -- _debug("SL"..(db.CollectedLoot[SelectedLoot].itemLink), 1)
      local gp1, gp2, ilvl = GP:GetValue(db.CollectedLoot[SelectedLoot].itemLink)
      return gp1;
  else 
    return 0 
  end
end

function EELoot:GetEligiblePlayers()
  _debug("GetEligiblePlayers")

  if not db.CollectedLoot[SelectedLoot] then return {} end
  if not db.CollectedLoot[SelectedLoot].interest then return {} end  
  
  ---- sort player interest into three tiers
  -- FIXME: brutal but transparent, refactor later
  local tier1 = {}
  local tier2 = {}
  local tier3 = {}

  for name, interest in pairs(db.CollectedLoot[SelectedLoot].interest) do
    if playerToBarIndex[name] then
      if interest['interest'] == "NEEDMAIN" then
        tinsert(tier1, {name=name, points=EEKarma:KarmaGetTotal(name)})
      elseif interest['interest'] == "NEEDOFF" then
        tinsert(tier2, {name=name, points=EEKarma:KarmaGetTotal(name)})
      elseif interest['interest'] == "GREEDMAIN" then
        tinsert(tier3, {name=name, points=0})
      elseif interest['interest'] == "GREEDOFF" then
        tinsert(tier3, {name=name, points=0})
      end
    end
  end 
  
  ---- pick a tier
  local r_tier = {}
  if #tier1 > 0 then      
    r_tier = tier1
  elseif #tier2 > 0 then    
    r_tier = tier2
  elseif #tier3 > 0 then    
    r_tier = tier3
  else -- otherwise return an empty table
    return {}
  end
  
  -- filter 3 and return
  local r_names = {}
  table.sort(r_tier, _sortEligiblePlayers)

  -- select roll tiers and init roll if diff is more than 1  
  for i, v in ipairs(r_tier) do
    if i > 1 then
      if r_tier[1].points - v.points > 1 then
        break
      else
        tinsert(r_names, v.name)
      end
    else
      tinsert(r_names, v.name)
    end
  end
  
  return r_names 
  
end



function EELoot:DeclareWinner()
  _debug("DeclareWinner")
  if not db.CollectedLoot[SelectedLoot] then return end
  if db.CollectedLoot[SelectedLoot].winner then return end    
  -- determine pretendent
  local pretendent
  if SelectedPlayer then
    pretendent = bars[SelectedPlayer].player
  else
    pretendent = _WinnerNames[1]
  end 
  
  ---- deduct karma if aplicable
  -- prevalidate entered karma  
  local t_karma = self.DeductKarma:GetText()
  if not string.find(t_karma, "^%s*[+-]*[%d]+%s*$") then _debug("> карма должна быть числом", 1); return end
  t_karma = (abs(tonumber(t_karma)))

  -- set winner
  db.CollectedLoot[SelectedLoot].winner = pretendent  
  

  local interestTable = {};
  interestTable['NEEDMAIN'] = 1;
  interestTable['NEEDOFF']  = 2;
  
  -- pay karma
  local interest = interestTable[db.CollectedLoot[SelectedLoot].interest[pretendent]['interest']];
  if (not interest) then 
    interest = 0;
  end;
  -- _debug(">interest is "..interest, 1);
  EEKarma:KarmaAdd(pretendent, t_karma, interest, db.CollectedLoot[SelectedLoot].itemLink)
  
  -- notify winner
  self:SendCommMessage("LSRA", "WINNER;"..pretendent..", "..db.CollectedLoot[SelectedLoot].itemLink, "RAID")
  self:CalculateWinner()
  self:DrawInterestAll()
end

function EELoot:CalculateWinner()
  _debug("CalculateWinner")
  wipe(_WinnerNames)
  _WinnerRoll = 0
  SelectedPlayer = nil
  if not db.CollectedLoot[SelectedLoot] then return end  
  if not db.CollectedLoot[SelectedLoot].winner then -- esli pobeditel' uzhe ne opredelen
    if not db.CollectedLoot[SelectedLoot].interest then return end
    -- calculate actual winner
    for player, interest in pairs(db.CollectedLoot[SelectedLoot].interest) do      
      if interest.totalroll then
        if interest.totalroll > _WinnerRoll then        
          _debug(">> new winner "..interest.totalroll.." ".._WinnerRoll.." "..player)
          -- risovat' igroka
          _WinnerRoll = interest.totalroll
          wipe(_WinnerNames)
          tinsert(_WinnerNames, player)
          --        
        elseif interest.totalroll == _WinnerRoll then
          _debug(">> new tie "..interest.totalroll.." ".._WinnerRoll.." "..player)
          tinsert(_WinnerNames, player)
        end
      end    
    end
    if #_WinnerNames == 1 then
      self.WinnerButton:SetText("Выиграл ".._WinnerNames[1])
      local size = self.WinnerButton:GetTextWidth()+30
      if size < 80 then size = 80; end
      self.WinnerButton:SetWidth(size)
      self.WinnerButton:Enable()
      self.DeductKarma:SetText(self:GetKarmaCost(_WinnerNames[1]))
      --
      self.GiveLootButton:SetText("Некому выдать") 
      local size = self.GiveLootButton:GetTextWidth()+30
      if size < 80 then size = 80; end
      self.GiveLootButton:SetWidth(size)
      self.GiveLootButton:Disable()      
    else
      -- ne opredelen pobeditel'
      self.WinnerButton:SetText("Победитель не определен")
      local size = self.WinnerButton:GetTextWidth()+30
      if size < 80 then size = 80; end
      self.WinnerButton:SetWidth(size)
      self.WinnerButton:Disable()
      self.DeductKarma:SetText('')
      --
      self.GiveLootButton:SetText("Некому выдать") 
      local size = self.GiveLootButton:GetTextWidth()+30
      if size < 80 then size = 80; end
      self.GiveLootButton:SetWidth(size)
      self.GiveLootButton:Disable()
    end
  else
    -- esli pobeditel' opredelen, vkljuchit' knopku vydachi, i zadiejblit' knopku opredelenija pobeditelja
    self.WinnerButton:SetText("Выиграл "..db.CollectedLoot[SelectedLoot].winner)
    local size = self.WinnerButton:GetTextWidth()+30
    if size < 80 then size = 80; end
    self.WinnerButton:SetWidth(size)
    self.WinnerButton:Disable()
    self.DeductKarma:SetText('')    
    --
    self.GiveLootButton:SetText("Выдать "..db.CollectedLoot[SelectedLoot].winner)
    local size = self.GiveLootButton:GetTextWidth()+30
    if size < 80 then size = 80; end
    self.GiveLootButton:SetWidth(size)    
    if _LootMode == 1 then self.GiveLootButton:Enable() end
  end
end

function EELoot:CalculateRoll(name, roll)
  if not db.CollectedLoot[SelectedLoot].interest then return end -- premature roll, item not defined
  if not db.CollectedLoot[SelectedLoot].interest[name] then return end -- not allowed to roll, did not declare interest
  if not db.CollectedLoot[SelectedLoot].interest[name].roll then return end -- roll = 0 mustbe preset to allow roll
  if db.CollectedLoot[SelectedLoot].interest[name].roll == 0 then -- if havent already rolled
    -- set and display roll ammount
    db.CollectedLoot[SelectedLoot].interest[name].roll = tonumber(roll)
    bars[playerToBarIndex[name]].Roll:SetText('+|cffffff00'..roll..'|r')
    
    -- calculate total with all respects
    local total
    -- needs use karma with their roll
    if db.CollectedLoot[SelectedLoot].interest[name].interest == "NEEDMAIN" or db.CollectedLoot[SelectedLoot].interest[name].interest == "NEEDOFF" then
      _debug(">>b "..db.CollectedLoot[SelectedLoot].interest[name].interest)
      total = roll + EEKarma:KarmaGetTotal(name)
    -- greeds do not use karma with their roll
    else
      _debug(">>nb "..db.CollectedLoot[SelectedLoot].interest[name].interest)
      total = roll
    end
    db.CollectedLoot[SelectedLoot].interest[name].totalroll = tonumber(total)
    bars[playerToBarIndex[name]].Total:SetText('|cffffffff'..total..'|r')    
  end    
end



function EELoot:GiveLoot()
  _debug("GiveLoot")
  if not db.CollectedLoot[SelectedLoot].winner then _debug("Некорректная попытка выдать не победителю" ,1); return end
  local pretendent = db.CollectedLoot[SelectedLoot].winner
  _debug("попытка выдать "..db.CollectedLoot[SelectedLoot].itemLink..", "..pretendent)
  for ci = 1, GetNumRaidMembers() do
    if (GetMasterLootCandidate(ci) == pretendent ) then
      for li = 1, GetNumLootItems() do
        if LootSlotIsItem(li) then
          if GetLootSlotLink(li) == db.CollectedLoot[SelectedLoot].itemLink then
            _message(GetLootSlotLink(li)..", "..pretendent, "Пытаюсь выдать")
            GiveMasterLoot(li, ci)
            return true
          end
        end
      end
    end
  end
  _debug("Не получилось выдать "..db.CollectedLoot[SelectedLoot].itemLink..", "..pretendent, 1)
  return false
end


function EELoot:LootAnnounceRaid()
  -- local linkstext = ''
  if #db.CollectedLoot > 0 then
    for i = 1, #db.CollectedLoot do    
      -- local iteminfo = db.CollectedLoot[i].itemLink
      -- -- silly
      -- if linkstext == '' then
      --   linkstext = iteminfo
      -- else
      --   linkstext = linkstext..' '..iteminfo
      -- end
      self:SendCommMessage("LSRA", "ANNOUNCE_LOOT;"..db.CollectedLoot[i].itemLink, "RAID")      
    end    
    -- self:SendCommMessage("LSRA", "ANNOUNCE_LOOT;"..linkstext, "RAID")    
  end
end

function EELoot:LootAnnounceGuild()
  -- local linkstext = ''
  if db.CollectedLoot.loottarget ~= "" then
    ChatThrottleLib:SendChatMessage("NORMAL", "LSRA", "Лут: "..db.CollectedLoot.loottarget, "GUILD")
  else
    ChatThrottleLib:SendChatMessage("NORMAL", "LSRA", "Лут: сундук", "GUILD")    
  end
  
  if #db.CollectedLoot > 0 then
    for i = 1, #db.CollectedLoot do
      ChatThrottleLib:SendChatMessage("NORMAL", "LSRA", db.CollectedLoot[i].itemLink, "GUILD")
    end
  end
end



function EELoot:OnlineMode()
  _debug("OnlineMode")
  _LootMode = 1
  self.LootStatus:SetBackdropColor(0.2,0.7,0.2,0.5)
  --
  if not db.CollectedLoot.loottarget then
    if UnitIsDead("target") and UnitIsEnemy("player", "target") and not UnitIsPlayer("unit") then  
      db.CollectedLoot.loottarget = UnitName("target")
    else
      db.CollectedLoot.loottarget = "Custom Loot"
    end
  end
  --
  self.LootTargetName:SetText(db.CollectedLoot.loottarget)
  self:DrawPlayerBars()
  self:CalculateWinner()
  self:DrawInterestAll()
end

function EELoot:OfflineMode()
  _debug("OfflineMode")
  _LootMode = 2
  self.GiveLootButton:Disable()
  self.LootStatus:SetBackdropColor(0.7,0.2,0.2,0.5)
end



function EELoot:CollectLoot()
  _debug("CollectLoot")
  -- smotrim est' li chto sobrat'
  local t_collecteditems = {}
  for i = 1, GetNumLootItems() do
    if LootSlotIsItem(i) then
      tinsert(t_collecteditems,{itemLink=GetLootSlotLink(i)})
    end
  end
  
  -- esli chto-to podobrali
  if #t_collecteditems > 0 then    
    for i, v in ipairs(t_collecteditems) do 
      for ti, tv in ipairs(db.CollectedLoot) do
        if v.itemLink == tv.itemLink then
          t_collecteditems[i].interest = db.CollectedLoot[ti].interest
          t_collecteditems[i].winner = db.CollectedLoot[ti].winner
          t_collecteditems[i].rolltype = db.CollectedLoot[ti].rolltype
          break
        end
      end
    end
    wipe(db.CollectedLoot)   
    db.CollectedLoot = t_collecteditems   

    UIDropDownMenu_Initialize(self.LootDropDownMenu, self.LootDropDownMenu_Initialize)
    SelectedLoot = 1
    UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, 1)
    -- 
    self.StandardRoll:Enable()
    self.QuickRoll:Enable()    
    self:OnlineMode()
    return #db.CollectedLoot
  else  
    -- pusto, zametaem sledy
    wipe(db.CollectedLoot)
    --
    UIDropDownMenu_Initialize(self.LootDropDownMenu, self.LootDropDownMenu_Initialize)
    SelectedLoot = 1
    UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, 1)
    --
    self:DeleteInterest()
    self:ClearInterest()
    self:OfflineMode()
    self.StandardRoll:Disable()
    self.QuickRoll:Disable() 
    self.ButtonStartRoll:Disable()   
    EERaidAdmin.Anchor:Hide()    
    return 0    
  end
  
end


function EELoot:ManualCollectLoot(lootLink)
  _debug("ManualCollectLoot")
  -- add custom item to roll list
  local t_collecteditems = {}
  tinsert(t_collecteditems,{itemLink=lootLink})
  
  -- esli chto-to podobrali
  if #t_collecteditems > 0 then    
    for i, v in ipairs(t_collecteditems) do 
      for ti, tv in ipairs(db.CollectedLoot) do
        if v.itemLink == tv.itemLink then
          t_collecteditems[i].interest = db.CollectedLoot[ti].interest
          t_collecteditems[i].winner = db.CollectedLoot[ti].winner
          t_collecteditems[i].rolltype = db.CollectedLoot[ti].rolltype
          break
        end
      end
    end
    wipe(db.CollectedLoot)   
    db.CollectedLoot = t_collecteditems   

    UIDropDownMenu_Initialize(self.LootDropDownMenu, self.LootDropDownMenu_Initialize)
    SelectedLoot = 1
    UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, 1)
    -- 
    self.StandardRoll:Enable()
    self.QuickRoll:Enable()    
    self:OnlineMode()
    return #db.CollectedLoot
  else  
    -- pusto, zametaem sledy
    wipe(db.CollectedLoot)
    --
    UIDropDownMenu_Initialize(self.LootDropDownMenu, self.LootDropDownMenu_Initialize)
    SelectedLoot = 1
    UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, 1)
    --
    self:DeleteInterest()
    self:ClearInterest()
    self:OfflineMode()
    self.StandardRoll:Disable()
    self.QuickRoll:Disable() 
    self.ButtonStartRoll:Disable()   
    EERaidAdmin.Anchor:Hide()    
    return 0    
  end
  
end




function EELoot:DeleteInterest(player)
  _debug("DeleteInterest")
  if not db.CollectedLoot[SelectedLoot] then return end  
  if not db.CollectedLoot[SelectedLoot].interest then return end
  if player then    
    if not db.CollectedLoot[SelectedLoot].interest[player] then return end
    wipe(db.CollectedLoot[SelectedLoot].interest[player])    
  else
    wipe(db.CollectedLoot[SelectedLoot].interest)
    db.CollectedLoot[SelectedLoot].winner = nil  
  end
end

function EELoot:ClearInterest()
  for i = 1, #bars, 1 do
    local i_r, i_g, i_b = _adjustColorToIndex(i, 0.25, 0.25, 0.25)
    bars[i].InterestPane.texture:SetTexture(0, 0, 0, 0)
    bars[i].InterestPane:SetBackdropColor(0, 0, 0, 0)
    bars[i].InterestButton:SetNormalTexture(nil)
    bars[i].InterestButton:SetText('')
    bars[i].texture:SetTexture(i_r, i_g, i_b, 0.5)
    bars[i]:SetBackdropColor(i_r, i_g, i_b, 0)
    bars[i].Roll:SetText('')
    bars[i].Total:SetText('')    
  end 
end

function EELoot:DrawInterest(player)
  _debug("DrawInterest: "..player)
    if self.Anchor:IsVisible() then
    -- valid bar check
    if not bars then return end  
    if not playerToBarIndex[player] then return end  
    if not (playerToBarIndex[player] <= __raidActivePlayers) then return end
      
    if not db.CollectedLoot[SelectedLoot].winner then
      if not db.CollectedLoot[SelectedLoot].rolltype then
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
        bars[playerToBarIndex[player]].InterestButton:SetText('')
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
        return
      else
        if not db.CollectedLoot[SelectedLoot].interest then
          bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
          bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
          bars[playerToBarIndex[player]].InterestButton:SetText('?')
          bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
          return
        else
          if not db.CollectedLoot[SelectedLoot].interest[player] then 
            bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
            bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
            bars[playerToBarIndex[player]].InterestButton:SetText('?')
            bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
            return
          end
        end        
      end
    end
    
    if not db.CollectedLoot[SelectedLoot].interest then return end
    if not db.CollectedLoot[SelectedLoot].interest[player] then return end
      
    if db.CollectedLoot[SelectedLoot].interest[player].roll then
      local roll      = db.CollectedLoot[SelectedLoot].interest[player].roll
      bars[playerToBarIndex[player]].Roll:SetText('+|cffffff00'..roll..'|r')
      local totalroll = db.CollectedLoot[SelectedLoot].interest[player].totalroll
      bars[playerToBarIndex[player]].Total:SetText('|cffffffff'..totalroll..'|r')
    end
    
    -- if db.CollectedLoot[SelectedLoot].interest[player].currentitem then
    --   bars[playerToBarIndex[player]].ItemText:SetText(db.CollectedLoot[SelectedLoot].interest[player].currentitem)
    --   bars[playerToBarIndex[player]].ItemText:Show()
    -- end
    
    if not db.CollectedLoot[SelectedLoot].winner then    
      -- poshli vse proverki - podbiraem interes igroka  
      local t_interest = db.CollectedLoot[SelectedLoot].interest[player]['interest']
      -- TODO: brutforsim :)
      if t_interest == "NEEDMAIN" then
        _debug("NEEDMAIN")
        --local i_r, i_g, i_b = _adjustColorToIndex(playerToBarIndex[player], 0.40, 0.10, 0.40)
        local i_r, i_g, i_b = 0.60, 0.10, 0.60
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(i_r,i_g,i_b,1)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
        bars[playerToBarIndex[player]].InterestButton:SetText("1N")
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
      elseif t_interest == "GREEDMAIN" then
        _debug("GREEDMAIN")
        --local i_r, i_g, i_b = _adjustColorToIndex(playerToBarIndex[player], 0.40, 0.10, 0.40)
        local i_r, i_g, i_b = 0.60, 0.10, 0.60
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(i_r,i_g,i_b,1)
        bars[playerToBarIndex[player]].InterestButton:SetText("1G")
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
      elseif t_interest == "NEEDOFF" then
        _debug("NEEDOFF")
        --local i_r, i_g, i_b = _adjustColorToIndex(playerToBarIndex[player], 0.10, 0.10, 0.50)
        local i_r, i_g, i_b = 0.10, 0.10, 0.60
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(i_r,i_g,i_b,1)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
        bars[playerToBarIndex[player]].InterestButton:SetText("2N")
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
      elseif t_interest == "GREEDOFF" then
        _debug("GREEDOFF")
        --local i_r, i_g, i_b = _adjustColorToIndex(playerToBarIndex[player], 0.10, 0.10, 0.50)
        local i_r, i_g, i_b = 0.10, 0.10, 0.60
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(i_r,i_g,i_b,1)
        bars[playerToBarIndex[player]].InterestButton:SetText("2G")
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
      elseif t_interest == "PASS" then
        _debug("PASS")
        --local i_r, i_g, i_b = _adjustColorToIndex(playerToBarIndex[player], 0.25, 0.25, 0.25)
        local i_r, i_g, i_b = 0.40, 0.40, 0.40
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(i_r,i_g,i_b,1)
        bars[playerToBarIndex[player]].InterestButton:SetText('P')
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture(nil)
      elseif t_interest == "TIMEOUT" then
        _debug("TIMEOUT")
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
        bars[playerToBarIndex[player]].InterestButton:SetText('')
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture("Interface\\Addons\\EERaidAdmin\\textures\\Time")
      elseif t_interest == "NA" then
        _debug("NA")
        bars[playerToBarIndex[player]].InterestPane.texture:SetTexture(0,0,0,0)
        bars[playerToBarIndex[player]].InterestPane:SetBackdropColor(0,0,0,0)
        bars[playerToBarIndex[player]].InterestButton:SetText('')
        bars[playerToBarIndex[player]].InterestButton:SetNormalTexture("Interface\\Addons\\EERaidAdmin\\textures\\Slash")
      end
    end
    
  end
end

function EELoot:DrawInterestAll()
  _debug("DrawInterestAll")  
  if self.Anchor:IsVisible() then
    self:ClearInterest()
    if db.CollectedLoot[SelectedLoot] then
      for i = 1, #raidPlayers do
        local name, class, subgroup, online = raidPlayers[i].name, raidPlayers[i].class, raidPlayers[i].subgroup, raidPlayers[i].online
        if subgroup <= __raidActiveGroups then self:DrawInterest(name) end
        if i == __raidActivePlayers then break end
      end
      -- draw winner
      if db.CollectedLoot[SelectedLoot].winner then
        local t_index = playerToBarIndex[db.CollectedLoot[SelectedLoot].winner]
        if t_index <= __raidActivePlayers then
          local i_r, i_g, i_b = _adjustColorToIndex(t_index, 0.50, 0.50, 0)
          bars[t_index].texture:SetTexture(0,0,0,0)
          bars[t_index]:SetBackdropColor(i_r,i_g,i_b,0.95)
        end
      elseif #_WinnerNames > 0 then        
        for i, player in ipairs(_WinnerNames) do   
          local t_index = playerToBarIndex[player]
          if t_index <= __raidActivePlayers then
            local i_r, i_g, i_b = _adjustColorToIndex(t_index, 0.50, 0.50, 0)
            bars[t_index].texture:SetTexture(0,0,0,0)
            bars[t_index]:SetBackdropColor(i_r,i_g,i_b,0.95)
          end
        end
      end
    end
  end
end

function EELoot:UpdateInterest(player, interest)
  _debug("UpdateInterest: "..player..", "..interest)  
  if not db.CollectedLoot[SelectedLoot] then return end      
  if not db.CollectedLoot[SelectedLoot].interest then
    _debug("> first interest")
    db.CollectedLoot[SelectedLoot].interest = {}
  end      
  db.CollectedLoot[SelectedLoot].interest[player] = {}
  db.CollectedLoot[SelectedLoot].interest[player]['interest'] = interest
  self:DrawInterest(player)
  self.ButtonStartRoll:Enable()
end

function EELoot:OnCommReceived(prefix, message, distribution, sender)
  _debug("OnCommReceived")
  local tokens = { strsplit(";", message) }
  if prefix == "LSRC" then 
    --
    if tokens[1] == "EQUIP" then
      if not (playerToBarIndex[sender] <= __raidActivePlayers) then return end
      if tokens[2] == "FAIL" then
        --db.CollectedLoot[SelectedLoot].interest[sender].currentitem = "Не найден в кэше у игрока, повторить?"
        bars[playerToBarIndex[sender]].ItemText:SetText("Не найден в кэше у игрока, повторить?")
        bars[playerToBarIndex[sender]].ItemText:Show()        
      else
        local itemInfo = GetItemInfo(tokens[2])
        local _, itemLink, _, _, _, _, _, _, _, _ = GetItemInfo(tokens[2])
        _debug("EQUIP POLL:"..sender..":"..tokens[2])
        if itemInfo then
          _debug("Could obtain item - drawing")
          --db.CollectedLoot[SelectedLoot].interest[sender].currentitem = itemLink
          bars[playerToBarIndex[sender]].ItemText:SetText(itemLink) 
          bars[playerToBarIndex[sender]].ItemText:Show()       
        else
          _debug("Could not obtain item")
          -- TODO:
          tempTooltip = CreateFrame("GameTooltip", "TempTooltip", UIParent, "GameTooltipTemplate")
          tempTooltip:SetHyperlink("item:".._getItemId(tokens[2])..":0:0:0:0:0:0:0")
          --db.CollectedLoot[SelectedLoot].interest[sender].currentitem = "Не найден в локальном кэше, повторить?"
          bars[playerToBarIndex[sender]].ItemText:SetText("Не найден в локальном кэше, повторить?")
          bars[playerToBarIndex[sender]].ItemText:Show()
        end
      end      
    elseif tokens[1] == "LOOT" then
      self:UpdateInterest(sender, tokens[2])
    end 
    ------------------------------------------------------------------   
  end
end

local function __________()
  -- ignore, IDE cheat
end

function EELoot:LootDropDownMenu_SelectLoot()
  _debug("LootDropDownMenu_SelectLoot")
  local ndb=this:GetID()
  UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, ndb)
  SelectedLoot=ndb
  self.StandardRoll:Enable()
  self.QuickRoll:Enable()  
  self:DrawPlayerBars()
  self:CalculateWinner()
  self:DrawInterestAll()
end

function EELoot:LootDropDownMenu_OnShow()
  _debug("LootDropDownMenu_OnShow")
  UIDropDownMenu_Initialize(self.LootDropDownMenu, self.LootDropDownMenu_Initialize)
  UIDropDownMenu_SetSelectedID(self.LootDropDownMenu, SelectedLoot)
  UIDropDownMenu_SetWidth(self.LootDropDownMenu, 300)
end

function EELoot:LootDropDownMenu_Initialize()
  _debug("LootDropDownMenu_Initialize")
  info_loot = {}
  info_loot.fontObject = "GameFontNormalLarge"
  if #db.CollectedLoot > 0 then    
    for i = 1, #db.CollectedLoot do
      info_loot.text = db.CollectedLoot[i].itemLink
      info_loot.checked = i == SelectedLoot
      info_loot.func = function() EELoot:LootDropDownMenu_SelectLoot() end
      -- info_loot.icon = "Interface\\Addons\\EERaidAdmin\\textures\\Slash" --TODO --Interface\\Buttons\\UI-GroupLoot-Pass-Up
      UIDropDownMenu_AddButton(info_loot)
    end
  else
    info_loot.text = "Нет Предмета"
    info_loot.checked = true
    UIDropDownMenu_AddButton(info_loot)
  end

end

function EELoot:OnInitialize()
  _debug("OnInitialize")
  
  self.db = LibStub("AceDB-3.0"):New("EERaidAdminDB")
  db = self.db.global
  
  if db.CollectedLoot == nil then db.CollectedLoot = {}; end
  --if db.CollectedLootInterest == nil then db.CollectedLootInterest = {}; end
  
  self:RegisterComm("LSRC")
  --
  self:RegisterBucketEvent("RAID_ROSTER_UPDATE", 1, "RAID_ROSTER_UPDATE")
  self:RegisterBucketEvent("CHAT_MSG_SYSTEM", 0.5, "CHAT_MSG_SYSTEM_SLOW")
  self:RegisterEvent("LOOT_OPENED")
  self:RegisterEvent("LOOT_CLOSED")
  self:RegisterEvent("LOOT_SLOT_CLEARED")
  self:RegisterEvent("PLAYER_TARGET_CHANGED")
  self:RegisterEvent("CHAT_MSG_SYSTEM")
  --
  self:CreateFrames()
  self:OfflineMode()
  if #db.CollectedLoot > 0 then
    self.StandardRoll:Enable()
    self.QuickRoll:Enable()
  end
  self.Anchor:Hide()
end

function EELoot:CreateFrames()
  --  
  --tempTooltip = CreateFrame("GameTooltip", nil, UIParent, "GameTooltipTemplate")

  self.Anchor = CreateFrame("Frame",nil,UIParent)
  self.Anchor:SetFrameStrata("HIGH")  
  self.Anchor:SetScript("OnShow", function() EELoot:OnShow() end )
  self.Anchor:SetScript("OnHide", function() EELoot:OnHide() end )
  
  self.LootStatus = CreateFrame("Frame", nil, self.Anchor)      
  self.LootStatus:SetPoint("TOPLEFT", self.Anchor, "TOPLEFT", 20, -40)
  self.LootStatus:SetPoint("TOPRIGHT", self.Anchor, "TOPRIGHT", -20, -40)
  self.LootStatus:SetBackdrop( {bgFile = "Interface\\Addons\\EERaidAdmin\\textures\\Stripes", 
                    edgeFile = nil, tile = true, tileSize = 32, edgeSize = nil, 
                    insets = { left = 0, right = 0, top = 0, bottom = 0 }});
  self.LootStatus:SetBackdropColor(0,0,0,0);
  self.LootStatus:SetHeight(55)
  
  -- first line of buttons
  local RollType = self.LootStatus:CreateFontString(nil,"ARTWORK","GameFontNormal")
        RollType:SetText("Тип ролла")
        RollType:SetPoint("TOPLEFT",self.LootStatus,"TOPLEFT",10,-5)
        
  self.LootTargetName = self.LootStatus:CreateFontString(nil,"ARTWORK","GameFontNormal")  
  self.LootTargetName:SetPoint("TOPRIGHT",self.LootStatus,"TOPRIGHT",-10,-5)  
      
  self.StandardRoll = CreateFrame("Button",nil,self.LootStatus,"OptionsButtonTemplate")
  self.StandardRoll:SetHeight(28)
  self.StandardRoll:SetText("Полный")
  self.StandardRoll:SetScript("OnClick", function() 
    EELoot:SendStandardRoll()
  end )
  self.StandardRoll:Disable()
  self.StandardRoll:SetPoint("BOTTOMLEFT",self.LootStatus,"BOTTOMLEFT", 5, 5)
  
  self.QuickRoll = CreateFrame("Button",nil,self.LootStatus,"OptionsButtonTemplate")
  self.QuickRoll:SetHeight(28)
  self.QuickRoll:SetText("Быстрый")
  self.QuickRoll:SetScript("OnClick", function() 
    EELoot:SendQuickRoll()
  end )
  self.QuickRoll:Disable()
  self.QuickRoll:SetPoint("LEFT",self.StandardRoll,"RIGHT",5,0)    
  
  self.LootDropDownMenu = CreateFrame("Button","LootDropDownMenu",self.LootStatus,"UIDropDownMenuTemplate")
  self.LootDropDownMenu:SetScript("OnDoubleClick", function()
    if IsShiftKeyDown() then
      EELoot:LootAnnounceGuild()
    else
      EELoot:CollectLoot()
    end
  end )
  self.LootDropDownMenu:SetScript("OnShow", function()    
    EELoot:LootDropDownMenu_OnShow()
  end )  
  self.LootDropDownMenu:SetPoint("BOTTOMRIGHT",self.LootStatus,"BOTTOMRIGHT", 10, 2)  

  self.BarList = CreateFrame("Frame", nil, self.Anchor) 
  self.BarList:SetPoint("TOPLEFT", self.LootStatus, "BOTTOMLEFT", 0, -20)
  self.BarList:SetPoint("TOPRIGHT", self.LootStatus, "BOTTOMRIGHT", 0, -20)
  self.BarList:SetHeight(500)
  
  -- second line of buttons
  self.ButtonStartRoll = CreateFrame("Button",nil,self.Anchor,"OptionsButtonTemplate")
  self.ButtonStartRoll:SetHeight(28)
  self.ButtonStartRoll:SetText("Победитель")
  self.ButtonStartRoll:SetScript("OnClick", function()
    EELoot:SendStartRoll()
  end )
  self.ButtonStartRoll:SetPoint("BOTTOMLEFT",self.Anchor,"BOTTOMLEFT",20,20)  
  --self.ButtonStartRoll:Disable()
  
  self.GiveLootButton = CreateFrame("Button",nil,self.Anchor,"OptionsButtonTemplate")
  self.GiveLootButton:SetHeight(28)
  self.GiveLootButton:SetText("Некому выдать")
  self.GiveLootButton:SetScript("OnClick", function()    
    EELoot:GiveLoot()
    EELoot:DrawInterestAll()
  end )
  self.GiveLootButton:SetPoint("BOTTOMRIGHT",self.Anchor,"BOTTOMRIGHT",-20,20)  
  self.GiveLootButton:Disable()
  
  self.WinnerButton = CreateFrame("Button",nil,self.Anchor,"OptionsButtonTemplate")
  self.WinnerButton:SetHeight(28)
  self.WinnerButton:SetText("Выиграл")
  self.WinnerButton:SetScript("OnClick", function()
    EELoot:DeclareWinner()    
    EELoot:DrawInterestAll()
  end )
  self.WinnerButton:SetPoint("RIGHT",self.GiveLootButton,"LEFT",-20,0)  
  self.WinnerButton:Disable()
  
  self.DeductKarma = CreateFrame("EditBox", "DeductKarma", self.Anchor, "InputBoxTemplate")  
  self.DeductKarma:SetWidth(40)
  self.DeductKarma:SetHeight(22)
  self.DeductKarma:SetAutoFocus(false)
  self.DeductKarma:ClearFocus()
  self.DeductKarma:SetPoint("RIGHT",self.WinnerButton,"LEFT",-5,0)
  
  local DeductKarmaLabel = self.Anchor:CreateFontString(nil,"ARTWORK","GameFontNormal")
        DeductKarmaLabel:SetText("—")
        DeductKarmaLabel:SetPoint("RIGHT",self.DeductKarma,"LEFT",-7,0)
end

function EELoot:OnShow()
  _debug("OnShow")
  self:UpdateRaidPlayerInfo()
  self:DrawPlayerBars()  
  self:CalculateWinner()
  self:DrawInterestAll()
end

function EELoot:OnHide()
  _debug("OnHide")  
end

function EELoot:OnEnable()
  _debug("OnEnable")
end

function EELoot:OnDisable()
  _debug("OnDisable")
end

Compare with Previous | Blame