--- Map Marker Button
--
local MapButton = {}
local addon, ns = ...
local ss = ns.SS

local CreateFrame, Minimap = ss.CreateFrame, Minimap
local math = math

local minimapShapes = {
  ["ROUND"] = {true, true, true, true},
  ["SQUARE"] = {false, false, false, false},
  ["CORNER-TOPLEFT"] = {false, false, false, true},
  ["CORNER-TOPRIGHT"] = {false, false, true, false},
  ["CORNER-BOTTOMLEFT"] = {false, true, false, false},
  ["CORNER-BOTTOMRIGHT"] = {true, false, false, false},
  ["SIDE-LEFT"] = {false, true, false, true},
  ["SIDE-RIGHT"] = {true, false, true, false},
  ["SIDE-TOP"] = {false, false, true, true},
  ["SIDE-BOTTOM"] = {true, true, false, false},
  ["TRICORNER-TOPLEFT"] = {false, true, true, true},
  ["TRICORNER-TOPRIGHT"] = {true, false, true, true},
  ["TRICORNER-BOTTOMLEFT"] = {true, true, false, true},
  ["TRICORNER-BOTTOMRIGHT"] = {true, true, true, false},
}

--- Creates a new map button.
--
function MapButton:New(angle)
  -- Create map button
  local button = CreateFrame("Button", ss._f.."MapButton", Minimap)

  button:SetWidth      (ss.private.MapMarker.size)
  button:SetHeight     (ss.private.MapMarker.size)
  button:SetFrameStrata(ss.retailClient and "LOW" or "MEDIUM")
  button.angle = angle or math.rad(225)
  
  ss.Extentions:MakeMovable(button)

  button:HookScript("OnClick", function()
    ss.Config:Toggle()
  end)
  
  ss.Extentions:Hook(button, "OnDragStart", function(self)
    self.dragging = true
  end)
  
  ss.Extentions:Hook(button, "OnDragStop", function(self)
    self.dragging = nil
  end)
  
  ss.Extentions:Hook(button, "OnUpdate", function(self)
    if self.dragging then
      self.angle = ss.Utils:AngleFromFrame(Minimap)
      self:Reposition()
    end
  end)
  
  -- Add the tooltip.
  ss.Utils:AddTooltip(button,
    "ANCHOR_NONE", {
      "RIGHT",
      button,
      "LEFT",
    }, {
      "Seamore Spheres",
      "",
      ss.T["open_menu"],
      ss.T["move_sphere"],
    })
  
  function button:Reposition()
    local x, y, q = math.cos(self.angle), math.sin(self.angle), 1
  
    -- Determine the Minimap quadrant.
    if x < 0 then q = q + 1 end
    if y > 0 then q = q + 2 end
    
    -- Check for a customized layout (shape).
    local minimapShape = GetMinimapShape and GetMinimapShape() or "ROUND"
    local quadTable = minimapShapes[minimapShape]
    
    -- Determine the position relative to the Minimap center.
    if quadTable[q] then
      x, y = x*80, y*80
    else
      local diagRadius = 103.13708498985 --math.sqrt(2*(80)^2)-10
      x = math.max(-80, math.min(x*diagRadius, 80))
      y = math.max(-80, math.min(y*diagRadius, 80))
    end
    
    -- Update values.
    ss.global.general.MapMarker.x = x
    ss.global.general.MapMarker.y = y
    ss.global.general.MapMarker.locationAngle = self.angle
    self:SetPoint("CENTER", Minimap, "CENTER", x, y)
  end

  button:SetHighlightTexture(ss.MapMarker.TEXTURE_HIGHLIGHT, "ADD")

  return button
end

ss.Utils.addModule("MapMarkerButton", MapButton)


