-- This file is part of AutoInvite
--
-- (C) 2014 Scott Yeskie (Sasky)
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

AutoInvite = AutoInvite or {}
AutoInvite.AddonId = "AutoInvite"

------------------------------------------------
--- Utility functions
------------------------------------------------
local function b(v) if v then return "T" else return "F" end end
local function nn(val) if val == nil then return "NIL" else return val end end
local function dbg(msg) if AutoInvite.debug then d("|c999999" .. msg) end end
local function echo(msg) CHAT_SYSTEM.primaryContainer.currentBuffer:AddMessage("|CFFFF00"..msg) end

AutoInvite.isCyrodiil = function(unit)
    if unit == nil then unit = "player" end
    dbg("Current zone: '" .. GetUnitZone(unit) .. "'")
    return GetUnitZone(unit) == "Cyrodiil"
end

------------------------------------------------
--- Event handlers
------------------------------------------------
AutoInvite.callback = function(_, messageType, from, message)
	if not AutoInvite.enabled or not AutoInvite.listening then
		return
	end

    --TODO: Switch to queue-based with timeouts so don't send out too many invites
	if GetGroupSize() >= AutoInvite.cfg.maxSize then
        echo("Group full. Disabling AutoInvite")
        AutoInvite.stopListening()
	end

	if string.lower(message) == AutoInvite.cfg.watchStr and from ~= nil and from ~= "" then
		if (messageType >= CHAT_CHANNEL_GUILD_1 and messageType <= CHAT_CHANNEL_OFFICER_5) then
			from = AutoInvite.guildLookup(messageType, from)
			if from == "" then return end
        end

        --TODO: Add friends list lookup

		from = from:gsub("%^.+", "")
        echo("Sending invite to " .. from)
		GroupInvite(from)
		GroupInviteByName(from)
	end

	--d("Checking message '" .. string.lower(message) .."' ?= '" .. AutoInvite.cfg.watchStr .."'")
end

AutoInvite.playerLeave = function()
    if AutoInvite.enabled and AutoInvite.cfg.restart and GetGroupSize() < AutoInvite.cfg.maxSize then
        echo("Now space in group. Restarted listening.")
        AutoInvite.startListening()
    end

    local unitName = GetUnitName(unitTag):gsub("%^.+", "")
    AutoInvite.kickTable[unitName] = nil
end

AutoInvite.offlineEvent = function(_, unitTag, connectStatus)
    local unitName = GetUnitName(unitTag):gsub("%^.+", "")
    if connectStatus then
        dbg(unitTag .. "/" .. unitName .. " has reconnected")
        AutoInvite.kickTable[unitName] = nil
    else
        dbg(unitTag .. "/" .. unitName .. " has disconnected")
        AutoInvite.kickTable[unitName] = GetTimeStamp()
    end
end

function AutoInvite.disbandEvent()
    if AutoInvite.enabled and AutoInvite.cfg.restart then
        echo("Group disbanded. Restarted listening.")
        AutoInvite.startListening()
    end
end

-- tick function: called every 15s
function AutoInvite.tick()
    AutoInvite.kickCheck()
end

------------------------------------------------
--- Main interface
------------------------------------------------
AutoInvite.disable = function()
	AutoInvite.enabled = false
    AutoInvite.stopListening()
    EVENT_MANAGER:UnregisterForUpdate("AutoInviteKickCheck")
    EVENT_MANAGER:UnregisterForEvent(AutoInvite.AddonId, EVENT_GROUP_DISBANDED)
end

AutoInvite.stopListening = function()
    EVENT_MANAGER:UnregisterForEvent(AutoInvite.AddonId, EVENT_CHAT_MESSAGE_CHANNEL)
    AutoInvite.listening = false
end

AutoInvite.startListening = function()
    if not AutoInvite.enabled then
        AutoInvite.enabled = true
        AutoInvite.checkOffline()
        EVENT_MANAGER:RegisterForUpdate("AutoInviteKickCheck", 1000, AutoInvite.tick)
        EVENT_MANAGER:RegisterForEvent(AutoInvite.AddonId, EVENT_GROUP_DISBANDED)
    end

	if not AutoInvite.listening and GetGroupSize() < AutoInvite.cfg.maxSize then
		--Add handler
		EVENT_MANAGER:RegisterForEvent(AutoInvite.AddonId, EVENT_CHAT_MESSAGE_CHANNEL, AutoInvite.callback)
		AutoInvite.listening = true
    end

    --First check. When option, will have to check option for disable
	echo("AutoInvite listening on string '" .. AutoInvite.cfg.watchStr .. "'")
end

------------------------------------------------
--- Initialization
------------------------------------------------
AutoInvite.init = function()
    EVENT_MANAGER:UnregisterForEvent("AutoInviteInit", EVENT_PLAYER_ACTIVATED)
    if AutoInvite.initDone then return end
    AutoInvite.initDone = true

    local def = {
        maxSize = 24,
        restart = false,
        cyrCheck = false,
        autoKick = false,
        kickDelay = 300,
        watchStr = "",
        showPanel = true,
    }
    AutoInvite.cfg = ZO_SavedVars:NewAccountWide("AutoInviteSettings", 1.0, "config", def)
    EVENT_MANAGER:RegisterForEvent(AutoInvite.AddonId, EVENT_GROUP_MEMBER_LEFT, AutoInvite.playerLeave)
    EVENT_MANAGER:RegisterForEvent(AutoInvite.AddonId, EVENT_GROUP_MEMBER_CONNECTED_STATUS, AutoInvite.offlineEvent)
    AutoInvite.listening = false
    AutoInvite.enabled = false
    AutoInviteUI.init()
end

EVENT_MANAGER:RegisterForEvent("AutoInviteInit", EVENT_PLAYER_ACTIVATED, AutoInvite.init)