local addonName, addon = ...

WZT = {};
WZT.waitingForTicket = false;
WZT.hasTicket = false;
WZT.ticketId = 0;
WZT.ticketStatus = "Open";
WZT.ticketCreated = "";
WZT.ticketModified = "";
WZT.ticketMessage = "";

WZT.minimapIcon = LibStub("LibDBIcon-1.0", true);
WZT.dataObject = LibStub:GetLibrary("LibDataBroker-1.1", true):NewDataObject(addonName, {
	type = "data source",
	text = "WoW Zone Tickets",
	icon = "Interface\\AddOns\\WZTickets\\Textures\\icon",
	OnClick = function() WZT:MinimapOnClick(); end,
});

function WZT:OnLoad()
	DEFAULT_CHAT_FRAME:AddMessage("|cffff0000["..addonName.."]: |cffffffffType \"/ticket\" or use the minimap button to submit a ticket.");
		
	WZTickets_Create:Hide();
	WZTickets_View:Hide();
	
	-- Minimap icon
	if not WZT.minimapIcon then return end
	if not WZTicketsLDBIconDB then WZTicketsLDBIconDB = {} end
	WZT.minimapIcon:Register(addonName, WZT.dataObject, WZTicketsLDBIconDB);
	WZT.minimapIcon:Show(addonName);
end

function WZT:ToggleRequest()
	if WZTickets_Create:IsVisible() then
		WZTickets_Create:Hide();
	else
		WZT.waitingForTicket = true;
		SendChatMessage(".wzticket myview", "GUILD");
	end
end

function WZT:MinimapOnClick()
	WZT:ToggleRequest();
end

function WZT:CreateSend()
	local text = WZTickets_Create.scrollFrame.editBox:GetText();
	local textSub = gsub(text, "\n", " ");
	
	SendChatMessage(".wzticket create "..textSub, "GUILD");
	
	WZT.hasTicket = true;
	
	WZTickets_Create:Hide();
	WZTickets_Create.scrollFrame.editBox:SetText("");
end

function WZT:CreateClose()
	WZTickets_Create:Hide();
end

function WZT:ViewUpdateSend()
	local editBox = WZTickets_View.scrollFrame.editBox;
	local text = editBox:GetText();
	local textSub = gsub(text, "\n", " ");
	
	editBox:ClearFocus();
	
	SendChatMessage(".wzticket myedit "..textSub, "GUILD");
	WZT.waitingForTicket = true;
	SendChatMessage(".wzticket myview", "GUILD");
end

function WZT:ViewTextChanged(editbox)
	local text = editbox:GetText();
	local textSub = gsub(text, "\n", " ");
	
	if editbox:GetNumLetters() >= 10 and WZT.ticketMessage ~= textSub then
		WZTickets_View.updateButton:Enable();
	else
		WZTickets_View.updateButton:Disable();
	end
end

function WZT:ViewClose()
	WZTickets_View:Hide();
end

function WZT:CancelTicket()
	SendChatMessage(".wzticket myclose", "GUILD");
	WZTickets_View:Hide();
end

function WZT:NewTicket()
	SendChatMessage(".wzticket myclose", "GUILD");
	WZTickets_View:Hide();
	WZTickets_Create:Show();
end

-- Callbacks
function WZT:OnNoTicketReceived()
	WZTickets_Create:Show();
end

function WZT:OnTicketReceived()
	if WZT.ticketStatus == "Open" or WZT.ticketStatus == "Complete" then
		WZTickets_View.statusText:SetText("|cffa9a9a9Status:|r |cff00ff00" .. WZT.ticketStatus .. "|r");
	else
		WZTickets_View.statusText:SetText("|cffa9a9a9Status:|r |cffff0000" .. WZT.ticketStatus .. "|r");
	end
	WZTickets_View.createdText:SetText("|cffa9a9a9Created: " .. WZT.ticketCreated .. "|r");
	WZTickets_View.modifiedText:SetText("|cffa9a9a9Last modified: " .. WZT.ticketModified .. "|r");
	WZTickets_View.scrollFrame.editBox:SetText(WZT.ticketMessage);
	
	if WZT.ticketStatus == "Complete" then
		WZTickets_View.updateButton:Hide();
		
		WZTickets_View.newButton:Enable();
		WZTickets_View.newButton:Show();
	else
		WZTickets_View.updateButton:Show();
		
		WZTickets_View.newButton:Disable();
		WZTickets_View.newButton:Hide();
	end
	
	WZTickets_View:Show();
end

function WZT.FormatTime(timeStr)
	local returnStr = "";
	
    local days = string.match(timeStr, "([0-9]*)d");
    if days then
        returnStr = days .. " days";
    else
		local hours = string.match(timeStr, "([0-9]*)h");
		if hours then
			returnStr = hours .. " hours";
		else
			local minutes = string.match(timeStr, "([0-9]*)m");
			if minutes then
				returnStr = minutes .. " min";
			else
				local seconds = string.match(timeStr, "([0-9]*)s");
				if seconds then
					returnStr = seconds .. " sec";
				end
			end
		end
	end
	
    return returnStr .. " ago";
end

-- Chat reader
local ORIG_ChatFrame_MessageEventHandler = ChatFrame_MessageEventHandler;

function ChatFrame_MessageEventHandler(self, event, ...)
    local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 = ...;
    local ActionTaken = false;

    -- check for system messages of interest
    if (event == "CHAT_MSG_SYSTEM") then
		if WZT.waitingForTicket then
			-- Read no ticket
			if string.find(arg1, "You dont have a ticket.") then
				WZT.hasTicket = false;
				WZT:OnNoTicketReceived();
				ActionTaken = true;
			else
				-- Read ticket main info
				local ticketId, status, createStr, lastModifiedStr = string.match(arg1, "^%|cffaaffaaTicket%|r:%|cffaaccff%s([0-9]+).%|r%s%|cff00ff00Status%|r:%|cff00ccff%s(.+)%|r%s%|cff00ff00Created%|r:%|cff00ccff%s([a-zA-Z0-9%s]+)%sago%|r%s%|cff00ff00Last%smodified%|r:%|cff00ccff%s([a-zA-Z0-9%s]+)%sago%|r$");

				if ticketId and status and createStr and lastModifiedStr then
					WZT.hasTicket = true;
					WZT.ticketId = tonumber(ticketId);
					WZT.ticketStatus = status;
					WZT.ticketCreated = WZT.FormatTime(createStr);
					WZT.ticketModified = WZT.FormatTime(lastModifiedStr);
					
					WZT:OnTicketReceived();
					
					ActionTaken = true;
				end
				
				-- Read ticket message
				local message = string.match(arg1, "^%|cff00ff00Ticket%sMessage%|r:%s%[(.+)%]%|r$");

				if message then
					WZT.hasTicket = true;
					WZT.ticketMessage = message;
					WZT.waitingForTicket = false;
					
					WZT:OnTicketReceived();
					
					ActionTaken = true;
				end
			end
		end
    end

    -- if nothing was done, just display the message
    if not ActionTaken then
        ORIG_ChatFrame_MessageEventHandler(self, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
    end
end

-- Initialization
local frame = CreateFrame("FRAME");
frame:RegisterEvent("ADDON_LOADED");

function frame:OnEvent(event, arg1)
    if event == "ADDON_LOADED" and arg1 == addonName then
        WZT:OnLoad();
    end
end

frame:SetScript("OnEvent", frame.OnEvent);

-- Slash commands
SLASH_WZTICKETS1, SLASH_WZTICKETS2 = '/ti', '/ticket';
function SlashCmdList.WZTICKETS(msg, editbox)
	WZT:ToggleRequest();
end