--[[
Author: Jarth
Filename: SummonAssistant.lua
Version: V1.2.0
]]--

-------------------------------------------------------------------------------------------------
--  Libraries --
-------------------------------------------------------------------------------------------------
local LAM2 = LibStub:GetLibrary("LibAddonMenu-2.0")

-------------------------------------------------------------------------------------------------
--  VARIABLE --
-------------------------------------------------------------------------------------------------
local ADDON_NAME = "SummonAssistant"
local ADDON_VERSION = 1.2
local ADDON_AUTHOR = "Jarth"
local ADDON_WEBSITE = ""
local SummonAssistant = {} -- this may seem odd, but it sets the access level for "SummonAssistant"
SummonAssistant.wm = GetWindowManager() -- we want to use whatever window manager the game is
SummonAssistant.name = ADDON_NAME
SummonAssistant.saCountUnlocked = GetTotalCollectiblesByCategoryType(COLLECTIBLE_CATEGORY_TYPE_ASSISTANT)
SummonAssistant.SA_Button = {}
SummonAssistant.Default = {
  left = CENTER,
  top = CENTER,
  centerColor = {0.88,0.88,0.88,0.4}, -- {red, green, blue, alpha}
  edgeColor = {0.57,0.57,0.57,0.6}, -- {red, green, blue, alpha}
  showFence = IsCollectibleUnlocked(300),
  showBanker = IsCollectibleUnlocked(267),
  showVendor = IsCollectibleUnlocked(301),
  useAccountSettings = true,
}

-------------------------------------------------------------------------------------------------
--  FUNCTIONS --
-------------------------------------------------------------------------------------------------
function SummonAssistant.saClicked(id)
  -- increment the counter by one
  if id > 0 then
    local id = GetCollectibleIdFromType(COLLECTIBLE_CATEGORY_TYPE_ASSISTANT, id);
    if IsCollectibleUnlocked(id) then
      UseCollectible(id)
    else
      UseCollectible(GetActiveCollectibleByType(COLLECTIBLE_CATEGORY_TYPE_ASSISTANT))
    end
  end
end

function SummonAssistant.initializeButtons()
  local position = 0
  for i = 1, SummonAssistant.saCountUnlocked do
    local id = GetCollectibleIdFromType(COLLECTIBLE_CATEGORY_TYPE_ASSISTANT, i)
    if SummonAssistant.isCollectibleEnabled(id) then
      local enabled = true
      if id > 0 then
        enabled = IsCollectibleUnlocked(id)
      end
      if SummonAssistant.SA_Button[i] == nil then
        SummonAssistant.SA_Button[i] = WINDOW_MANAGER:CreateControlFromVirtual("SA_Button", SA_FrameBackdrop, "SA_Button", i)
        SummonAssistant.SA_Button[i]:SetId(i)
      end
      SummonAssistant.setupButton(i, SummonAssistant.SA_Button[i], id, enabled)
      SummonAssistant.SA_Button[i]:SetHidden(false)
      SummonAssistant.SA_Button[i]:ClearAnchors()
      SummonAssistant.SA_Button[i]:SetAnchor(TOPLEFT, SA_FrameBackdrop, TOPLEFT, 10+60*(position), 10)
      position = position + 1
    else
      if SummonAssistant.SA_Button[i] == nil then
      else
        SummonAssistant.SA_Button[i]:SetHidden(true)
      end
    end
  end
end

function SummonAssistant.setButtonFrameWidth()
  local saWidth = 0
  if IsCollectibleUnlocked(300) and SummonAssistant.savedVariables.showFence  then saWidth = saWidth + 60 end
  if IsCollectibleUnlocked(267) and SummonAssistant.savedVariables.showBanker then saWidth = saWidth + 60 end
  if IsCollectibleUnlocked(301) and SummonAssistant.savedVariables.showVendor then saWidth = saWidth + 60 end
  SA_Frame:SetHidden(saWidth == 0)
  SA_Frame:SetWidth(saWidth)
  SA_FrameBackdrop:SetWidth(saWidth)
end

function SummonAssistant.isCollectibleEnabled(id)
  local result = true
  if id == 300 and not SummonAssistant.savedVariables.showFence  then result = false end
  if id == 267 and not SummonAssistant.savedVariables.showBanker then result = false end
  if id == 301 and not SummonAssistant.savedVariables.showVendor then result = false end
  return result
end

function SummonAssistant.setupButton(i, SA_Button, id, enabled)
  local SA_ButtonTexture = SummonAssistant.wm:GetControlByName("SA_Button"..i.."Texture")
  if SA_ButtonTexture == nil then
  else
    if enabled then
      if id == 300 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_fence_01.dds")
      elseif id == 267 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_banker_01.dds")
      elseif id == 301 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_vendor_01.dds")
      end
      SA_Button:SetHandler("OnClicked", function(self) SummonAssistant.saClicked(SA_Button:GetId()) end)
    else
      if id == 300 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_fence_01_empty.dds")
      elseif id == 267 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_banker_01-empty.dds")
      elseif id == 301 then SA_ButtonTexture:SetTexture("/esoui/art/icons/assistant_vendor_01_empty.dds")
      else
      SA_Button:SetAlpha(0)
      end
    end
  end
end

function SummonAssistant.saRestorePosition()
  local top = SummonAssistant.savedVariables.top
  local left = SummonAssistant.savedVariables.left
  SA_Frame:ClearAnchors()
  SA_Frame:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, left, top)
end

function SummonAssistant.createHotkeySelections()
  if IsCollectibleUnlocked(300) then
    ZO_CreateStringId('SI_BINDING_NAME_SummonAssistant_Assistant_Fence', 'Fence')
  end
  if IsCollectibleUnlocked(267) then
    ZO_CreateStringId('SI_BINDING_NAME_SummonAssistant_Assistant_Banker', 'Banker')
  end
  if IsCollectibleUnlocked(301) then
    ZO_CreateStringId('SI_BINDING_NAME_SummonAssistant_Assistant_Vendor', 'Vendor')
  end
end

-- Global accessed function, allowing OnMoveStop to find the function.
function SummonAssistant_OnMoveStop()
  SummonAssistant.savedVariables.top = SA_Frame:GetTop()
  SummonAssistant.savedVariables.left = SA_Frame:GetLeft()
end

function SummonAssistant.RestorePanel()
  -- Set width of SA_Frame
  SummonAssistant.setButtonFrameWidth()
  -- Creates and setup of buttons
  SummonAssistant.initializeButtons()
  -- Restore position of bar
  SummonAssistant.saRestorePosition()
end

-------------------------------------------------------------------------------------------------
--  Menu Functions --
-------------------------------------------------------------------------------------------------
function SummonAssistant.CreateSettingsWindow()
	local panelData = {
		type = "panel",
		name = "Summon Assistant",
		displayName = "Summon Assistant",
		author = "Jarth",
    version = tostring(ADDON_VERSION),
		slashCommand = "/sa",
		registerForRefresh = true,
		registerForDefaults = true,
	}
	local cntrlOptionsPanel = LAM2:RegisterAddonPanel("SummonAssistant", panelData)

	local optionsData = {
		[1] = {
			type = "header",
			name = "Summon Assistant Settings"
		},
		[2] = {
			type = "description",
			text = "Here you can adjust how the summon assistant works."
		},
		[3] = {
			type = "checkbox",
			name = "Use account settings",
			tooltip = "When ON the account settings will be used. When OFF character settings will be used.",
			default = SummonAssistant.Default.useAccountSettings,
			getFunc = function() return SummonAssistant.savedVariables.useAccountSettings end,
			setFunc = function(newValue)
        --Apply value to existing variable
			  SummonAssistant.savedVariables.useAccountSettings = newValue;
			  if newValue then
				  SummonAssistant.savedVariables = ZO_SavedVars:NewAccountWide("SummonAssistant_Account", ADDON_VERSION, nil, SummonAssistant.Default)
			  else
				  SummonAssistant.savedVariables = ZO_SavedVars:New("SummonAssistant_Character", ADDON_VERSION, nil, SummonAssistant.Default)
			  end
        --Apply value to new variable
			  SummonAssistant.savedVariables.useAccountSettings = newValue;
			  SA_FrameBackdrop:SetCenterColor(unpack(SummonAssistant.savedVariables.centerColor))
			  SA_FrameBackdrop:SetEdgeColor(unpack(SummonAssistant.savedVariables.edgeColor))
			  SummonAssistant.RestorePanel()
			end,
		},
		[4] = {
			type = "submenu",
			name = "Colors",
			tooltip = "Allows you to change colors.",
			controls = {
			[1] = {
			  type = "description",
			  text = "Here you can adjust the colors."
			},
			[2] = {
			  type = "colorpicker",
			  name = "Backdrop Color",
			  default = SummonAssistant.Default.centerColor,
			  tooltip = "Changes the color of the background.",
			  getFunc = function() return unpack( SummonAssistant.savedVariables.centerColor ) end,
			  setFunc = function(r,g,b,a)
          SummonAssistant.savedVariables.centerColor = {r,g,b,a}
          SA_FrameBackdrop:SetCenterColor(r,g,b,a)
			  end,
			width = "half"
			},
			[3] = {
				type = "colorpicker",
				name = "Frame Color",
				default = SummonAssistant.Default.edgeColor,
				tooltip = "Changes the color of the frame.",
				getFunc = function() return unpack( SummonAssistant.savedVariables.edgeColor ) end,
				setFunc = function(r,g,b,a)
					SummonAssistant.savedVariables.edgeColor = {r,g,b,a}
					SA_FrameBackdrop:SetEdgeColor(r,g,b,a)
				end,
				width = "half"
				}
			},
    },
    [5] = {
      type = "submenu",
      name = "Visibility",
      tooltip = "Allows you to choose what assistant buttons you wants to see.",
      controls = {
        [1] = {
          type = "description",
          text = "Select assistant buttons you want enabled."
        },
        [2] = {
          type = "checkbox",
          name = "Show fence",
          tooltip = "When ON the fence button will be visible. When OFF the fence button will not be visible (disabled if locked for the account).",
          default = SummonAssistant.Default.showFence,
          disabled = not IsCollectibleUnlocked(300),
          getFunc = function() return SummonAssistant.savedVariables.showFence end,
          setFunc = function(newValue)
             SummonAssistant.savedVariables.showFence = newValue
             SummonAssistant.RestorePanel()
			    end,
        },
        [3] = {
          type = "checkbox",
          name = "Show banker",
          tooltip = "When ON the banker button will be visible. When OFF the banker button will not be visible (disabled if locked for the account).",
          default = SummonAssistant.Default.showBanker,
          disabled = not IsCollectibleUnlocked(267),
          getFunc = function() return SummonAssistant.savedVariables.showBanker end,
          setFunc = function(newValue)
             SummonAssistant.savedVariables.showBanker = newValue
             SummonAssistant.RestorePanel()
			    end,
        },
        [4] = {
          type = "checkbox",
          name = "Show vendor",
          tooltip = "When ON the vendor button will be visible. When OFF the vendor button will not be visible (disabled if locked for the account).",
          default = SummonAssistant.Default.showVendor,
          disabled = not IsCollectibleUnlocked(301),
          getFunc = function() return SummonAssistant.savedVariables.showVendor end,
          setFunc = function(newValue)
             SummonAssistant.savedVariables.showVendor = newValue
             SummonAssistant.RestorePanel()
			    end,
        },
      }
		},
	}
	LAM2:RegisterOptionControls("SummonAssistant", optionsData)
end

function SummonAssistant:Initialize()
  -- Load saved values..
	SummonAssistant.savedVariables = ZO_SavedVars:New("SummonAssistant_Character", ADDON_VERSION, nil, SummonAssistant.Default)
  if SummonAssistant.savedVariables.useAccountSettings then
    SummonAssistant.savedVariables = ZO_SavedVars:NewAccountWide("SummonAssistant_Account", ADDON_VERSION, nil, SummonAssistant.Default)
  end
  SummonAssistant.RestorePanel()
  -- Create Hotkey selections for assistants.
  SummonAssistant.createHotkeySelections()
  -- Create menu variables.
  -- ToDo - Merge the following with with setButtonFrameWidth && initializeButtons && saRestorePosition
  SummonAssistant.CreateSettingsWindow()
  SA_FrameBackdrop:SetCenterColor(unpack(SummonAssistant.savedVariables.centerColor))
  SA_FrameBackdrop:SetEdgeColor(unpack(SummonAssistant.savedVariables.edgeColor))
  -- ToDo - End.
  EVENT_MANAGER:UnregisterForEvent("SummonAssistant", EVENT_ADD_ON_LOADED)
end

-- Then we create an event handler function which will be called when the "addon loaded" event
-- occurs. We'll use this to initialize our addon after all of its resources are fully loaded.
function SummonAssistant.OnAddOnLoaded(event, addonName)
  -- The event fires each time *any* addon loads - but we only care about when our own addon loads.
  if addonName == SummonAssistant.name then
    SummonAssistant:Initialize()
  end
end

-- Load Event
-- We unregistered this at the end of the loadCC function for optimization.
-- Here we register it (after all the functions).
-- EVENT_MANAGER:RegisterForEvent("SummonAssistant", EVENT_ADD_ON_LOADED, SummonAssistant.saLoad)
EVENT_MANAGER:RegisterForEvent(SummonAssistant.name, EVENT_ADD_ON_LOADED, SummonAssistant.OnAddOnLoaded)
-- EVENT_MANAGER:RegisterForEvent("SummonAssistant Click", EVENT_GLOBAL_MOUSE_DOWN, SummonAssistant.saClicked) -- Edit by Mitsarugi, addon wont work without this line of code