Quantcast
local _, addon = ...
local dragFrame = addon:NewModule("DragFrame")

local MIN_RESIZE_WIDTH = 128
local MAX_RESIZE_WIDTH = 512

dragFrame.frame = DefaultCastingBar_DragFrame

local function savePositionAndDimensions(self)
	if not addon.db.profile.position then
		addon.db.profile.position = {}
	end
	local point, _, relpoint, x, y = self:GetPoint()
	addon.db.profile.position = { point, relpoint, x, y }
	addon.db.profile.width = self:GetWidth()
end

local function initPositionAndDimensions()
	local position = addon.db.profile.position
	if position then
		local point, relpoint, x, y = unpack(position)
		dragFrame.frame:ClearAllPoints()
		dragFrame.frame:SetPoint(point, UIParent, relpoint, x, y)
	end
	dragFrame.frame:SetSize(addon.db.profile.width, addon.barMaxHeight)
	dragFrame.frame.resizeButton:SetSize(addon.barMaxHeight, addon.barMaxHeight)
end

function dragFrame:OnInitialize()
	addon.db.RegisterCallback(addon, "OnProfileChanged", initPositionAndDimensions)
	addon.db.RegisterCallback(addon, "OnProfileCopied", initPositionAndDimensions)
	addon.db.RegisterCallback(addon, "OnProfileReset", initPositionAndDimensions)

	initPositionAndDimensions()

	SLASH_DEFAULTCASTINGBAR1 = "/dcb"
	SlashCmdList["DEFAULTCASTINGBAR"] = function(input)
		if dragFrame.frame:IsVisible() then
			dragFrame.frame:Hide()
			dragFrame.frame.resizeButton:Hide()
		else
			dragFrame.frame:Show()
			dragFrame.frame.resizeButton:Show()
		end
	end

	self.frame:SetBackdropColor(0, 1, 0, 0.5)
	self.frame.text = _G[self.frame:GetName().."Pos"]

	self.frame:EnableMouse(true)

	self.frame:SetResizable(true)
	self.frame:SetMinResize(MIN_RESIZE_WIDTH, addon.barMaxHeight)
	self.frame:SetMaxResize(MAX_RESIZE_WIDTH, addon.barMaxHeight)

	self.frame:SetMovable(true)
	self.frame:SetClampedToScreen(true)
	self.frame:Hide()
end

dragFrame.frame:RegisterForDrag("LeftButton")
dragFrame.frame:SetScript("OnDragStart", function(self, button)
	if button == "LeftButton" then
		self:StartMoving()
	end
end)

dragFrame.frame:SetScript("OnDragStop", function(self)
	savePositionAndDimensions(self)

	self:StopMovingOrSizing()
end)

dragFrame.frame:SetScript('OnUpdate', function(self)
	local x, y = self:GetLeft(), self:GetBottom()
	if x and y then
		self.text:SetText(("Left: %d Bottom: %d"):format(x , y))
	end
end)

dragFrame.frame.resizeButton:SetScript('OnMouseDown', function(self)
	self:SetButtonState("PUSHED", true)

	self:GetHighlightTexture():Hide()

	dragFrame.frame:StartSizing("BOTTOMRIGHT")
end)

dragFrame.frame.resizeButton:SetScript('OnMouseUp', function(self)
	self:SetButtonState("NORMAL", false)

	self:GetHighlightTexture():Show()

	savePositionAndDimensions(dragFrame.frame)

	dragFrame.frame:StopMovingOrSizing()
end)