--- Configuration Panel
--
local AddOnName, nsVars = ...
local ss = nsVars.SS

local CustomDropDownMenu_SetText = CustomDropDownMenu_SetText
local InterfaceOptionsFrame_Show = InterfaceOptionsFrame_Show
local CreateFrame = ss.CreateFrame

ss["Config"] = ss["Config"] or {}

--- Creates the main config panel.
--
function ss:InitializeConfigPanel()
  -- Create the config panel
  local tabNav = SJTabPanel:NewInterfaceOption(
      AddOnName, nil, nil,
      ss.FontObjects.FontExo2SemiBold,
      ss.FontObjects.FontExo2SemiBold,
      ss.SharedMedia.miscTextures.gradientCircleLg,
      ss.SharedMedia.miscTextures.gradientCircleLg)

  tabNav:HookScript("OnShow", function(self)
    if ss.Config.shouldReload then
      ss.Config.shouldReload = nil
      self:SetSelectedIndex(self:GetSelectedIndex())
    end
  end)

  if not ss.retailClient then
    -- Fake global mouse events to close menus.
    tabNav:HookScript("OnClick", function(self, ...)
      if HandleGlobalMouseEvent then
        HandleGlobalMouseEvent(...)
      end
    end)
  end

  ss.Config = tabNav:AddTab(ss._f .. "Config_General", ss.T["tab_label_general"], function()
    CustomDropDownMenu_SetText(ss.Config.buttonFrame.SmoothAnimationsDropdown, ss.T["menu_item_smooth_animations_" .. ss.global.general.smoothAnimations])
  end)

  function ss.Config:IsVisible()
    -- return the value from the tab panel.
    return tabNav:IsVisible()
  end

  -- Provide access to required SJTabPanel functions.
  function ss.Config:SetHotTab(...)
    return tabNav:SetHotTab(...)
  end

  function ss.Config:AddTab(...)
    return tabNav:AddTab(...)
  end

  function ss.Config:Close()
    if self:IsVisible() then
      -- Close the interface panel.
      InterfaceOptionsFrame_Show()

      if GameMenuFrame:IsShown() then
        -- Close the GameMenuFrame
        ToggleGameMenu()
      end
    end
  end

  function ss.Config:Toggle()
    if not self:IsVisible() then
      -- Open interface panel to main config.
      PlaySound(SOUNDKIT and SOUNDKIT.IG_SPELLBOOK_OPEN or "SPELLBOOKOPEN", "master")
      InterfaceOptionsFrame_Show()
      InterfaceOptionsFrame_OpenToCategory(AddOnName)
    else
      self:Close()
    end
  end

  -- Add the container.
  ss.Config.widgetFrame = ss.ConfigTools.getWidgetContainer(ss.Config, "ConfigWidgetFrame")

  -- Add the version.
  ss.Config.widgetFrame.version = ss.Config.widgetFrame:CreateFontString(ss._f .. "Version")
  ss.Config.widgetFrame.version:SetFontObject(ss.FontObjects.Exo2Medium14)
  ss.Config.widgetFrame.version:SetPoint("BOTTOMRIGHT", -15, 15)
  ss.Config.widgetFrame.version:SetSize(150, 25)
  ss.Config.widgetFrame.version:SetText(ss.t("lbl_version", ss.version))
  ss.Config.widgetFrame.version:SetJustifyV("BOTTOM")
  ss.Config.widgetFrame.version:SetJustifyH("RIGHT")

  -- Add the title
  ss.Config.widgetFrame.Title = ss.ConfigTools.createTitle(ss.T["config_title_general"], ss.Config.widgetFrame)

  -- Add the button container
  ss.Config.buttonFrame = CreateFrame("Frame", ss._f .. "cfg_button_frame", ss.Config)
  ss.Config.buttonFrame:SetAllPoints(ss.Config)

  -- Add the track combat check button and click event
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "TrackCombatCheckButton",
    text = ss.T["chk_track_combat"],
    checked = ss.global.track.combat,
    onClick = function(self)
      if not self:GetChecked() and ss.Layout:InCombat() then
        ss.Layout:EndCombat()
      end

      ss.global.track.combat = self:GetChecked()

      if self:GetChecked() and ss.Layout:InCombat() then
        ss.Layout:StartCombat()
      end
    end,
  })

  -- Add the show artwork check button and click event
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "ShowArtworkCheckButton",
    text = ss.T["chk_show_artwork"],
    checked = ss.global.show.artwork,
    onClick = function(self)
      if self:GetChecked() == true then
        ss.PendingTask.remove("hideArtwork")
        ss.PendingTask.add("showArtwork", function()
          ss.Layout:ShowArtwork(true)
          ss.global.show.artwork = true
        end, ss.T["chk_show_artwork"])
      else
        ss.PendingTask.remove("showArtwork")
        ss.PendingTask.add("hideArtwork", function()
          ss.Layout:ShowArtwork(false)
          ss.global.show.artwork = false
        end, ss.T["msg_hide_artwork"])
      end
    end,
  })

  -- Add the map marker visibility checkbox
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "ShowMapMarkerCheckButton",
    text = ss.T["chk_show_map_marker"],
    checked = ss.global.general.MapMarker.show,
    onClick = function(self)
      if self:GetChecked() == true then
        ss.PendingTask.remove("hideMapMarker")
        ss.PendingTask.add("showMapMarker", function()
          ss.global.general.MapMarker.show = true
          ss.MapMarker:Show(ss.global.general.MapMarker.show)
        end, ss.T["chk_show_map_marker"])
      else
        ss.PendingTask.remove("showMapMarker")
        ss.PendingTask.add("hideMapMarker", function()
          ss.global.general.MapMarker.show = false
          ss.MapMarker:Show(ss.global.general.MapMarker.show)
        end, ss.T["msg_hide_map_marker"])
      end
    end,
  })

  -- Add the smooth animate check button and click event
  local smoothOptions = {
    "off",
    "fast",
    "med",
    "slow",
  }

  ss.ConfigTools.addWidget({
    type = "DropDown",
    parent = ss.Config.buttonFrame,
    name = "SmoothAnimationsDropdown",
    text = ss.T["menu_label_smooth_animations"],
    defaultText = ss.global.general.smoothAnimations and ss.T["menu_item_smooth_animations_" .. ss.global.general.smoothAnimations] or "",
    init = function(_, level)
      for _, v in ss.Utils.pairsByKeys(smoothOptions) do
        local stuff = {
          fontObject = "Exo2Medium12",
        }

        stuff.text = ss.T["menu_item_smooth_animations_" .. v]
        stuff.value = v
        stuff.checked = (v == ss.global.general.smoothAnimations)
        stuff.func = function(_)
          CustomDropDownMenu_SetText(ss.Config.buttonFrame.SmoothAnimationsDropdown, ss.T["menu_item_smooth_animations_" .. v])
          ss.global.general.smoothAnimations = v
          CloseCustomDropDownMenus()
        end

        securecall("CustomDropDownMenu_AddButton", stuff, level)
      end
    end,
  })

  -- Add the use pet sphere check button and click event
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "UsePetSphereCheckButton",
    text = ss.T["chk_track_pet"],
    checked = ss.global.track.pet,
    onClick = function(self)
      if self:GetChecked() == true then
        ss.PendingTask.remove("hidePetSphere")
        ss.PendingTask.add("usePetSphere", function()
          ss.global.track.pet = true
          ss.Layout:TrackPet(true and ss.petAvail)
        end, ss.T["msg_show_pet_sphere"])
      else
        ss.PendingTask.remove("usePetSphere")
        ss.PendingTask.add("hidePetSphere", function()
          ss.global.track.pet = false
          ss.Layout:TrackPet(false and ss.petAvail)
        end, ss.T["msg_hide_pet_sphere"])
      end
    end,
  })

  -- Add the use power tracker check button and click event
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "UsePowerTrackerCheckButton",
    text = ss.T["chk_track_additional_resource"],
    checked = ss.global.track.additionalResource,
    onClick = function(self)
      if self:GetChecked() == true then
        ss.PendingTask.remove("hidePowerTracker")
        ss.PendingTask.add("usePowerTracker", function()
          ss.global.track.additionalResource = true
          ss.Layout:TrackAdditionalResource(true and ss.ClassResources.hasSecondaryResource())
        end, ss.T["msg_show_additional_resource"])
      else
        ss.PendingTask.remove("usePowerTracker")
        ss.PendingTask.add("hidePowerTracker", function()
          ss.global.track.additionalResource = false
          ss.Layout:TrackAdditionalResource(false and ss.ClassResources.hasSecondaryResource())
        end, ss.T["msg_hide_additional_resource"])
      end
    end,
  })

  -- Add the show resource gradients checkbox.
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "ShowResourceGradientsCheckButton",
    text = ss.T["chk_show_resource_gradients"],
    checked = ss.global.show.gradient,
    onClick = function(self)
      -- Add as a pending task to avoid issues manipualting frames during combat.
      if self:GetChecked() == true then
        ss.PendingTask.remove("hideGradients")
        ss.PendingTask.add("showGradients", function()
          ss.Layout:ShowGradients(true)
        end, ss.T["msg_show_resource_gradients"])
      else
        ss.PendingTask.remove("showGradients")
        ss.PendingTask.add("hideGradients", function()
          ss.Layout:ShowGradients(nil)
        end, ss.T["msg_hide_resource_gradients"])
      end
    end,
  })

  -- Add the track pet battle check button and click event.
  if ss.retailClient then
    ss.ConfigTools.addWidget({
      type = "Checkbox",
      parent = ss.Config.buttonFrame,
      name = "TrackPetBattleCheckButton",
      text = ss.T["chk_hide_spheres_during_pet_battles"],
      checked = ss.global.track.petBattles,
      onClick = function(self)
        if self:GetChecked() == true then
          ss.PendingTask.remove("dontTrackPetBattle")
          ss.PendingTask.add("trackPetBattle", function()
            ss.global.track.petBattles = true

            if ss.isInPetBattle then
              ss:PET_BATTLE_OPENING_START()
            end
          end)
        else
          ss.PendingTask.remove("trackPetBattle")
          ss.PendingTask.add("dontTrackPetBattle", function()
            if ss.isInPetBattle then
              ss:PET_BATTLE_CLOSE()
              ss.isInPetBattle = true
            end

            ss.global.track.petBattles = false
          end)
        end
      end,
    })
  end

  -- Add the show player frame check button.
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "ShowBlizzPlayerFrameCheckButton",
    text = ss.T["chk_show_blizzard_frames"],
    checked = ss.global.show.playerFrame,
    onClick = function(self)
      if self:GetChecked() == true then
        ss.PendingTask.remove("hidePlayerFrame")
        ss.PendingTask.add("showPlayerFrame", function()
          ss.global.show.playerFrame = true
          ss.Layout:UpdatePlayerFrame()
        end, ss.T["chk_show_blizzard_frames"])
      else
        ss.PendingTask.remove("showPlayerFrame")
        ss.PendingTask.add("hidePlayerFrame", function()
          ss.global.show.playerFrame = false
          ss.Layout:UpdatePlayerFrame()
        end, ss.T["msg_hide_blizzard_frames"])
      end
    end,
  })

  -- Add the hide in combat check button.
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "HideOnCombatCheckButton",
    text = ss.T["chk_hide_on_combat"],
    checked = ss.global.general.hideOnCombat,
    onClick = function(self)
      ss.global.general.hideOnCombat = self:GetChecked()
    end,
  })

  -- Add the hide in combat check button.
  ss.ConfigTools.addWidget({
    type = "Checkbox",
    parent = ss.Config.buttonFrame,
    name = "FadeMicroSpheresCheckButton",
    text = ss.T["chk_fade_micro_spheres"],
    checked = ss.global.general.fadeMicroSpheres,
    onClick = function(self)
      ss.global.general.fadeMicroSpheres = self:GetChecked()

      ss.Layout:UpdateMicroSphereTextures(ss.profile.microResourceFillTextureGroups[2], ss.profile.microResourceFillTextures[2], "mainResource")
      ss.Layout:UpdateMicroSphereTextures(ss.profile.microResourceFillTextureGroups[1], ss.profile.microResourceFillTextures[1])
    end,
  })

  -- Load additional config panels.
  self:InitializeConfigPreviewPanel()
  self:InitializeConfigMicroSpheresPanel()
  self:InitializeConfigProfilePanel()
end
