local GC = select(2, ...)

local Session = {}
GC.Session = Session

local private = {
    currentSession = nil,

    pauseStart = nil,
    sessionPause = 0,

    sessionIsRunning = false
}

-- wow api
local GetBestMapForUnit, GetUnitName, GetRealmName, GetMapInfo =
    C_Map.GetBestMapForUnit, GetUnitName, GetRealmName, C_Map.GetMapInfo

-- lua api
local time, tonumber = time, tonumber

function Session.New()
    GC.Debug.Log("NewSession")

    -- Save the current session to history before starting a new one
    if private.sessionIsRunning and private.currentSession then
        GC.SessionHistory.SaveSession()
    end

    private.PrepareNewSession()
    GC.SessionHistory.StartTracking()
    GC.UI.ClearLootCollectedList()
    GC.UI.ClearLastNoteworthyItemUI()
    GC.UI.RefreshUIs()
end

-- pause session (pause and refresh ui)
function Session.Pause()
    GC.Debug.Log("pauseSession")

    private.pauseStart = time()

    -- ui refresh
    GC.UI.RefreshUIs()
end

-- restart session (add pause to sessionPause and refresh ui)
function Session.Restart()
    GC.Debug.Log("restartSession")

    -- Safety: if not paused, nothing to restart
    if not private.pauseStart then
        GC.Debug.Log("Restart called but session was not paused — ignoring")
        return
    end

    -- calc pause add add to sessionPause
    private.sessionPause = private.sessionPause + (time() - private.pauseStart)
    private.pauseStart = nil

    -- ui refresh
    GC.UI.RefreshUIs()
end

function Session.IsRunning()
    return private.sessionIsRunning -- and private.pauseStart == nil
end

function Session.IsPaused() return private.pauseStart ~= nil end

-- Stop the current session. History is saved, timer stops.
-- The user must press Play to start a new session.
function Session.Stop()
    GC.Debug.Log("stopSession")
    if not private.sessionIsRunning then return end

    -- Save history before stopping
    if private.currentSession then
        GC.SessionHistory.SaveSession()
    end

    private.sessionIsRunning = false
    private.pauseStart = nil
    private.sessionPause = 0

    -- Clear the loot list UI so the window shows a clean state
    GC.UI.ClearLootCollectedList()
    GC.UI.ClearLastNoteworthyItemUI()
    GC.UI.RefreshUIs()
end

-- start a new session
function Session.Start(showMainUI)
    --    GC.SetGallywixCoinsDisabled(false)

    if not Session.IsRunning() then
        GC:Print("Start Session")

        local zoneInfo = GetMapInfo(GetBestMapForUnit("player"))
        zoneInfo = zoneInfo and zoneInfo.name
        GC.Debug.Log("  mapID=%s (%s)", GetBestMapForUnit("player"), zoneInfo)

        private.sessionIsRunning = true
        private.PrepareNewSession()
        GC.SessionHistory.StartTracking()
        GC.KillTracker.ResetCLEUState()

        -- show main window
        GC.UI.ShowMainWindow(showMainUI)
    end
end

function Session.GetPauseStart() return private.pauseStart end

function Session.GetSessionPause() return private.sessionPause end

function Session.GetCurrentSession(key)
    if not key then return private.currentSession end
    return private.currentSession[key]
end

function Session.SetCurrentSession(key, value)
    private.currentSession[key] = value
end

function private.PrepareNewSession()
    GC.Debug.Log("prepareNewSession")
    --    GC.Debug.Log("  savedLoot: %s items", GC.Util.tablelength(private.savedLoot))
    GC.UI.UpdateLiteWindowUI() -- pass to Update Lite Window to reset session and make value zero

    -- start: prepare session
    private.currentSession = {
        start = time(),
        mapID = GetBestMapForUnit("player"),
        settings = {
            qualityFilter = tonumber(GC.GetFromDb("notification",
                                                  "qualityFilter")),
            -- gat = tonumber(GC.GetFromDb("general", "goldAlertThreshold")),
            gatA = tonumber(GC.GetFromDb("notification", "goldAlertThresholdA")),
            gatB = tonumber(GC.GetFromDb("notification", "goldAlertThresholdB")),
            gatC = tonumber(GC.GetFromDb("notification", "goldAlertThresholdC")),
            priceSource = GC.GetFromDb("pricesource", "source")
        },
        noteworthyItems = {},
        kills = {},
        totalKills = 0,
        uniqueKills = 0,
        liv = 0,
        vendorSoldCurrencyUI = 0,
        livGroup = 0,
        player = GetUnitName("player", true) .. "-" .. GetRealmName()
    }
    GC.UI.UpdateLiteWindowUI()

    private.sessionPause = 0
    private.pauseStart = nil

    private.sessionIsRunning = true
    -- end: prepare session (for statistics)

    -- reset saved variables
    GallywixCoinsDB.global.session = ""
    GallywixCoinsDB.global.location = ""
    GallywixCoinsDB.global.loot = ""

end

