--[[CTRaid commands for FuBar
	Initial Version by MetaHawk aka Urshurak
	Updated/Modified by ArcaneFoam aka Keita @ Ysera-US
	Compatible with CT_RaidAssist v2.001
]]

-- Local Objects
local Tablet = AceLibrary("Tablet-2.0")     -- Tooltip-style display
local Dewdrop = AceLibrary("Dewdrop-2.0");  -- Clean dropdown menu interface
local L = AceLibrary("AceLocale-2.2"):new("CTRaidFu")

-- Dropdown Menu Creation (thanks FarmerFu)
local MenuOpts = {
    handler = CTRaidFu,
	type = "group",
	args = {
		converto = {
			-- Volver el Party un Raid
			type = "execute",
			order = 1,
			name = L["Convert Party to Raid"],
			desc = L["Converts the Party to a Raid,"].."|cFFFF8C00"..L[" (requires Party Leader Status)"],
			func = function() ConvertToRaid() self:Update() end,
			disabled = function() return (GetNumPartyMembers() == 0) or (not UnitIsPartyLeader("player")) end,
		},
        res = {
            -- Toggle Resurection Monitor
            type = "toggle", 
            order = 2,
			name = L["Resurection Monitor"],
            desc = L["Shows or hides the Resurrection Monitor"],
            get = "IsShowResMonitor",
		    set = "ToggleShowResMonitor",
			-- Only if in Raid
			disabled = function() return (GetNumRaidMembers() == 0) end
	    },
        status = {
            -- Show Status Monitor
            type = "toggle", 
            order = 3,
			name = L["Show Status Monitor"],
            desc = L["Shows or hides the Satus Monitor"],
			get = "IsShowStatusMonitor",
			set = "ToggleShowStatusMonitor",
			-- Only if in Raid
			disabled = function() return (GetNumRaidMembers() == 0) end
		},
        --[[targets = {
            type = "execute", 
            order = 4,
		    name = L["Target Management"],
            desc = L["Main Tank Configuration"],
			func = function() ExecuteChatCommand("/tm") end,
		), ]] 
        groups = {
            -- Show/hide groups
            type = "group",
            order = 5, 
            name = L["Groups"],
            desc = L["Shows or hides the Raid Groups"],
            args = {
                showall = {
                    type = "toggle",
                    order = 5.1,
                    name = L["Show All"],
                    desc = L["Show all groups"],
                    get = "IsShowAll",
                    set = "ToggleShowAll",
                },
                show = {
                    type = "execute",
                    order = 5.2,
                    name = L["Show Groups"],
                    desc = L["Show Raid Groups"],
                    func = "ShowGroups",
                },
                hide = {
                    type = "execute",
                    order = 5.3, 
                    name = L["Hide Groups"],
                    desc = L["Hide All Groups"],
                    func = function() ExecuteChatCommand("/rahide") end,
                },
            },
			-- Only if in Raid
			disabled = function() return (GetNumRaidMembers() == 0) end
        },            
		raid = {
            type = "group",
            order = 6,
            name= L["Raid Managment"],
            desc = L["Raid Managment Functions"].."|cFFFF8C00"..L[" (requires Leader or Promoted Status)"],
			args = {
				promote = {
					type = "execute",
					order = 6.1,
					name = L["Promote"],
					desc = L["Promotes Player to Assistant Status"],
					func = function() PromoteToAssistant("playertarget")  end,	
				},
				demote = {
					type = "execute",
					order = 6.2,
					name = L["Demote"],
					desc = L["Demotes Player from Assistant Status"],
					func = function() DemoteAssistant("playertarget")  end,		
				},
                quiet = {
                    type = "toggle",
                    order = 6.3,
                    name = L["Quiet Raid"],
                    desc = L["Stop the raid from talking while leaders talk"],
                    get = "IsQuiet",
                    set = "ToggleQuiet",
                },
                update = {
                    -- Update Raid Status
                    type = "execute",
                    order = 6.4,
                    name = L["Update Status"],
                    desc = L["Update the Raid Status"],
                    func = function() ExecuteChatCommand("/raupdate") end,
                },
                keyword = {
                    -- Autoinvite Keyword Settings
                    type = "group", 
                    order = 6.5,
                    name = L["Autoinvite"],
                    desc = L["Automatically invites people whispering you the set keyword"],
                    args = {
                        change = {
                            type = "text",
                            order = 6.51,
                            name = L["Change Keyword"],
                            desc = L["Set a new Keyword"],
                            get = "GetKeyword",
                            set = "ChangeKeyword",
                            usage = L["<New Keyword>"],
                        },
                        disable = {
                            type = "execute",
                            order = 6.52,
                            name = L["Turn off"],
                            desc = L["Disable Autoinvite"],
                            func = "ChangeKeyword",
                            passValue = "off",
                        },
                    },
                },
                invites = {
                    type = "group",
                    order = 6.6,
                    name = L["Guild Invitations"],
                    desc = L["Invite Guild Members to Raid"],
                    args = {
                        allguild = {
                            type = "toggle", 
                            order = 6.61, 
                            name = L["All Members"],
                            desc = L["Invite All Guild Members"],
                            get = "IsAllGuildies",
                            set = "ToggleAllGuildies",
                            isRadio = true,
                        },
                        zoneguilde = {
                            type = "toggle", 
                            order = 6.62, 
                            name = L["Members in Zone"],
                            desc = L["Invite Guild Members in your own Zone"],
                            get = "IsZoneGuildies",
                            set = "ToggleZoneGuildies",
                            isRadio = true,
                        },
                        minlevel = {
                            type = "range", 
                            order = 6.63, 
                            name = L["Min Level"],
                            desc = L["Set the Minimun Level to receive the Invite"],
                            min = 20,
                            max = 69,
                            step = 1,
                            get = "IsInviteMinLevel",
                            set = "SetInviteMinLevel",
                        },
                        mmaxlevel = {
                            type = "range", 
                            order = 6.64, 
                            name = L["Max Level"],
                            desc = L["Set the Maximum Level to receive the Invite"],
                            min = 21,
                            max = 70,
                            step = 1,
                            get = "IsInviteMaxLevel",
                            set = "SetInviteMaxLevel",
                        },
                        send = {
                            type = "execute",
                            order = 6.65,
                            name = L["Send Invitations"],
                            desc = L["This will Invite Guild Members according to the choosen parameters"],
                            func = "TossInvites",
                        },
                    },
                },
                vote = {
                    type = "text",
                    order = 6.6,
                    name = L["Ask for Votes"],
                    desc = L["Performs a vote, asking the raid for their opinion on the question. Results are broadcasted to raid chat after 30 seconds"],
                    get = false,
                    set = "AskVote",
                    usage = L["<Question>"],
                },
                disband = {
                    type = "execute",
                    order = 6.7,
                    name = "|cFFFF0000"..L["Disband Raid"],
                    desc = L["Disbands the Raid"], 
			        func = function() ExecuteChatCommand("/radisband") end,
                },
            },
			-- Dissabled if u are not the Guild Leader or an Officer
			disabled = function() if CT_RA_Level >= 1 then return false else return true end end,
        },
        check = {
            type = "group",
            order = 7,
            name = L["Check Functions"],
            desc = L["Status Check Functions"].."|cFFFF8C00"..L[" (requires Leader or Promoted Status)"],
            args = {
                raready = {
                    type = "execute",
                    order = 7.1,
                    name = L["Ready Check"],
                    desc = L["Performs a ready check, asking all CTRA users if they are ready"],
                    func = function() CT_RA_CheckReady() end,
                },
                rarly = {
                    type = "execute",
                    order = 7.2,
                    name = L["Rly Check"],
                    desc = L["Performs a rly check, asking all CTRA users if they are rly"],
                    func = function() CT_RA_CheckRly() end,
                },
		        radur = {
                    type = "execute",
                    order = 7.3,
                    name = L["Durability Check"],
                    desc = L["Performs a durability check, which shows every CTRA member's durability percent"],
                    func = function() ExecuteChatCommand("/radur") end,
                },
		        rereg = {
                    type = "execute",
                    order = 7.4,
                    name = L["Reagent Check"],
                    desc = L["Performs a reagent check, which shows every CTRA member's reagent count"],
                    func = function() ExecuteChatCommand("/rareg") end,
                },
                raresist = {
                    type = "execute",
                    order = 7.5,
                    name = L["Resistance Check"],
                    desc = L["Performs a resistance check, which shows every CTRA member's resistances"],
                    func = function() ExecuteChatCommand("/raresist") end,
                },
                raitem = {
                    type = "text",
                    order = 7.6,
                    name = L["Item Check"],
                    desc = L["Allows to see everyone in raid who has the item listed"],
                    get = false,
                    set = "CheckItem",
                    usage = L["<ItemName> or <[Item Link]>"],
                },
                razone = {
                    type = "execute",
                    order = 7.7,
                    name = L["Zone Check"],
                    desc = L["Performs a zone check, which shows every CTRA member outside of your zone"],
                    func = function() ExecuteChatCommand("/razone") end,
                },
                raversion = {
                    type = "execute", 
                    order = 7.8,
                    name = L["Version Check"],
                    desc = L["Performs a version check, which shows every member's CTRA version"],
                    func = function() ExecuteChatCommand("/raversion") end,
                },
            },
			-- Dissabled if u are not the Guild Leader or an Officer
			disabled = function() if CT_RA_Level >= 1 then return false else return true end end,
			
        },
        --[[ boss = {
            type = "group", 
            order = 1.7,
            name = L"Boss Functions"],
            desc = L["CTRaid_Assist Boss Functions"],
			args = {
                type = "execute",
                order = 1.51,
                name = L["Start Ragnaros Timer"],
                desc = L["Start Ragnaros Timer"],
			    func = function() ExecuteChatCommand("/ragstart") end,
		
		},]]
        options = {
            -- Options Window
            type = "execute",
			order = 8,
			name = L["CTRaid Options"],
            desc = L["Shows the options dialog"],
			func = function() CT_RAMenuFrame:Show(); end,
		},
        changelog = {
            -- Latest version changes
		    type = "execute",
            order = 9,
			name = L["Current Change Log"],
            desc = L["View the CTRaid Change Log"],
			func = function() ExecuteChatCommand("/ralog") end,
		},
        help = {
            -- Show help window
            type = "execute",
            order = 10,
            name = L["Help"],
            desc = L["Show CTRaid Help window"],
			func = function() ExecuteChatCommand("/rahelp") end,
		},
    },
}

CTRaidFu = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0", "FuBarPlugin-2.0");

CTRaidFu.hasIcon = true;
CTRaidFu.version = GetAddOnMetadata("FuBar_CTRaidFu","Version");
CTRaidFu.category = "Interface Enhancements";
CTRaidFu.hasNoText = true;
CTRaidFu.defaultPosition = "RIGHT";
CTRaidFu.OnMenuRequest = MenuOpts

CTRaidFu:RegisterDB("CTRaidFuDB")
CTRaidFu:RegisterDefaults("profile", {
	showwindows = {
		res = false,
		status = false,
	},
    showall = false,
    invites = {
        all = false,
        zone = false,
        minlevel = 35,
        maxlevel = 55,
    },
    quiet = false,
    rsinput = {
        show = false,
        xOfs = 0,
        yOfs = 0,
        saved = false,
    },
})

function CTRaidFu:OnInitialize()
    -- If on Raid
    if GetNumRaidMembers() ~= 0 then
        -- Open Resuraction Monitor?
        if self.db.profile.showwindows.res then 
			if ( GetNumRaidMembers() > 0 ) then
				CT_RA_ResFrame:Show();
			end
			CT_RAMenu_Options["temp"]["ShowMonitor"] = 1;
        else
			CT_RA_ResFrame:Hide();
			CT_RAMenu_Options["temp"]["ShowMonitor"] = nil;
        end
        -- Is Raid Quiet?
        if self.db.profile.quiet then
			if ( CT_RA_Level >= 1 ) then
				ExecuteChatCommand("/raquiet")
			end
        end
    end
end

-- Actions when Tool is Clicked with Left Button (Fubar Default)
function CTRaidFu:OnClick()
	if(IsShiftKeyDown()) then
        -- Do a Ready Check
		CT_RA_CheckReady();
	elseif(IsControlKeyDown()) then
        -- Do a Rly Check
        CT_RA_CheckRly();
    elseif(IsAltKeyDown()) then
        -- Do a Durability Check
        ExecuteChatCommand("/radur");
	else
        -- Open the CTRaid Options
		CT_RAMenuFrame:Show();
	end
end

-- Mouseover menu
function CTRaidFu:OnTooltipUpdate()
    -- Get the list of Instances the player is saved to
	if(GetNumSavedInstances() > 0) then
        -- There is at least 1 instance
		cat = Tablet:AddCategory(
            -- Title
			"text", L["\nSaved Instances:"],
            -- Number of Columns
			"columns", 2,
            -- Color of Colum 1
			"child_textR", 1,
			"child_textG", 0,
			"child_textB", 1,
            -- Color of Colum 2
			"child_text2R", 1,
			"child_text2G", 0.85,
			"child_text2B", 0
		)
        -- Add the instances to the list (box)
		for i=1, GetNumSavedInstances() do
			local name, ID, remaining = GetSavedInstanceInfo(i);
			remaining = SecondsToTime(remaining);
			cat:AddLine("text", name, "text2", remaining);
			cat:AddLine("text2", "|cff00ff00"..ID);
		end
	else
        -- No instances saved
		local cat = Tablet:AddCategory(
			"text", L["\nSaved Instances:"],
			"child_textR", 1,
			"child_textG", 0,
			"child_textB", 0
		)
		cat:AddLine("text", L["No saved instances found"])
	end
    -- Tooltip
	cat = Tablet:AddCategory(
		"text", "Hint:",
		"columns", 2,
		"child_textR", 0,
		"child_textG", 1,
		"child_textB", 0,
		"child_text2R", r,
		"child_text2G", g,
		"child_text2B", b
	)
	cat:AddLine("text", "Click:", "text2", L["CTRaid Options"])
	cat:AddLine("text", "ShiftClick:", "text2", L["Ready Check"])
	cat:AddLine("text", "CtrlClick:", "text2", L["Rly Check"])
    cat:AddLine("text", "AtlClick:", "text2", L["Durability Check"])
end

-- Handle the Res Monitor Window
function CTRaidFu:IsShowResMonitor()
	return self.db.profile.showwindows.res
end

function CTRaidFu:ToggleShowResMonitor()
	self.db.profile.showwindows.res = not self.db.profile.showwindows.res
	self:Update()
    if self.db.profile.showwindows.res then 
        -- ExecuteChatCommand("/rares show")
		if ( GetNumRaidMembers() > 0 ) then
			CT_RA_ResFrame:Show();
		end
		CT_RAMenu_Options["temp"]["ShowMonitor"] = 1;
    else
        -- ExecuteChatCommand("/rares hide")
		CT_RA_ResFrame:Hide();
		CT_RAMenu_Options["temp"]["ShowMonitor"] = nil;
    end
	return self.db.profile.showwindows.res
end

-- Handle the Status Monitor Window
function CTRaidFu:IsShowStatusMonitor()
	return self.db.profile.showwindows.status
end

function CTRaidFu:ToggleShowStatusMonitor()
	self.db.profile.showwindows.status = not self.db.profile.showwindows.status
	self:Update()
    if self.db.profile.showwindows.res then 
        -- ExecuteChatCommand("/rares show")
		if ( GetNumRaidMembers() > 0 ) then
			CT_RAMetersFrame:Show();
		end
    else
        -- ExecuteChatCommand("/rares hide")
		CT_RAMetersFrame:Hide();
    end
	return self.db.profile.showwindows.res
end

-- Handle Keyword
function CTRaidFu:GetKeyword()
    local kw = CT_RAMenu_Options["temp"]["KeyWord"];
    if kw then
        return "|cFF00FF00"..kw
    else
        return "|cFFFFFF00<Disabled>"
    end
end

function CTRaidFu:ChangeKeyword(keyword)
    ExecuteChatCommand("/rakeyword "..keyword)
    self:Update()
end

-- Manage Groups
function CTRaidFu:IsShowAll ()
    return self.db.profile.showall
end

function CTRaidFu:ToggleShowAll()
    self.db.profile.showall = not self.db.profile.showall
    self:Update()
    return self.db.profile.showall
end

function CTRaidFu:ShowGroups()
    if self.db.profile.showall then
        ExecuteChatCommand("/rashow all")
    else
        ExecuteChatCommand("/rashow")
    end
end

-- Manage Invites
function CTRaidFu:IsAllGuildies()
    return self.db.profile.invites.all
end

function CTRaidFu:ToggleAllGuildies()
    self.db.profile.invites.all = not self.db.profile.invites.all
    self.db.profile.invites.zone = false
    self:Update()
    return self.db.profile.invites.all
end

function CTRaidFu:IsZoneGuildies()
    return self.db.profile.invites.zone
end

function CTRaidFu:ToggleZoneGuildies()
    self.db.profile.invites.zone = not self.db.profile.invites.zone
    self.db.profile.invites.all = false
    self:Update()
    return self.db.profile.invites.zone
end

function CTRaidFu:IsInviteMinLevel()
    return self.db.profile.invites.minlevel
end

function CTRaidFu:SetInviteMinLevel(level)
    self.db.profile.invites.minlevel = level
    self:Update()
end

function CTRaidFu:IsInviteMaxLevel()
    return self.db.profile.invites.maxlevel
end

function CTRaidFu:SetInviteMaxLevel(level)
    self.db.profile.invites.maxlevel = level
    self:Update()
end

function CTRaidFu:TossInvites ()
    if self.db.profile.invites.all then
		-- ExecuteChatCommand("/rainvite "..self.db.profile.invites.minlevel.."-"..self.db.profile.invites.maxlevel)
		CT_RA_ZoneInvite = nil;
		CT_RA_Invite(self.db.profile.invites.minlevel.."-"..self.db.profile.invites.maxlevel);
    else
		-- ExecuteChatCommand("/razinvite "..self.db.profile.invites.minlevel.."-"..self.db.profile.invites.maxlevel)
		CT_RA_ZoneInvite = 1;
		CT_RA_Invite(self.db.profile.invites.minlevel.."-"..self.db.profile.invites.maxlevel);
    end
end

-- Raid Managment
function CTRaidFu:IsQuiet ()
    return self.db.profile.quiet
end

function CTRaidFu:ToggleQuiet()
    self.db.profile.quiet = not self.db.profile.quiet
    ExecuteChatCommand("/raquiet")
    self:Update()
end

function CTRaidFu:AskVote (question)
	CT_RA_CheckVote(question)
    self:Update()
end

function CTRaidFu:CheckItem (item)
    ExecuteChatCommand("/raitem "..item)
end


-- Execute the /command in Chat
function ExecuteChatCommand(arg)
	if( not DEFAULT_CHAT_FRAME ) then return end
	DEFAULT_CHAT_FRAME.editBox:SetText(arg);
	ChatEdit_SendText(DEFAULT_CHAT_FRAME.editBox);
end

