WoWStudyFunction = {}
WoWStudyUI = {}
WoWStudyGlobal = {}

function WoWStudyFunction.ClearAllSessionAnalytics()
    WoWStudySaved.sessions = {}
end

function WoWStudyFunction.ClearLifetimeStatistics()
    WoWStudySaved.userInformation.lifetimeCorrect = 0
    WoWStudySaved.userInformation.lifetimeAnswered = 0
end

---
-- Load in External Decks, including external cards
---
function WoWStudyFunction.LoadExternalDecks()
    for globalName, value in pairs(_G) do  
        if type(value) == "table" and globalName:match("^deck_") then
            local deckName = globalName:gsub("^deck_", "")
            
            if WoWStudySaved.decks[deckName] and WoWStudySaved.decks[deckName].source == "internal" then
                print("Deck " .. deckName .. " already exists in the internal decks. Skipping.")
            else
                local existingDeck = WoWStudySaved.decks[deckName]
                local deck = {
                    name                         = deckName,
                    isSelected                   = (existingDeck and existingDeck.isSelected ~= nil) and existingDeck.isSelected or true,
                    cardsByQuestion              = existingDeck and existingDeck.cardsByQuestion or {},
                    source                       = "external",
                    creationTime                 = existingDeck and existingDeck.creationTime or time(),
                    totalCorrect                 = existingDeck and existingDeck.totalCorrect or 0,
                    totalIncorrect               = existingDeck and existingDeck.totalIncorrect or 0,
                    totalIncorrect               = existingDeck and existingDeck.totalIncorrect or 0,
                    totalAnswered                = existingDeck and existingDeck.totalAnswered or 0,
                    tags                         = existingDeck and existingDeck.tags or {},
                    deckIcon                     = existingDeck and existingDeck.deckIcon or "",q
                }

                if existingDeck and existingDeck.isSelected ~= nil then
                    deck.isSelected = existingDeck.isSelected -- Preserve the true/false value
                else
                    deck.isSelected = true -- Default to true if nil
                end

                WoWStudySaved.decks[deckName] = deck

                -- Load cards from the external file into the deck
                for i, c in ipairs(value) do
                    local existingCard = WoWStudySaved.decks[deckName].cardsByQuestion[c.question]
                    local card = {
                        compositeKey          = existingCard and existingCard.compositeKey or deckName .. ":" .. c.question,
                        question              = existingCard and existingCard.question or c.question,
                        answer                = c.answer,
                        type                  = c.type,
                        choices               = c.choices or {},
                        lastTime              = existingCard and existingCard.lastTime or 0,
                        spacedRepetitionLevel = existingCard and existingCard.spacedRepetitionLevel or 0,
                        totalCorrect          = existingCard and existingCard.totalCorrect or 0,
                        totalIncorrect        = existingCard and existingCard.totalIncorrect or 0,
                        totalAnswered         = existingCard and existingCard.totalAnswered or 0,
                        deckName              = deckName,
                        source                = "external",
                        creationTime          = existingCard and existingCard.creationTime or time(),
                        history               = existingCard and existingCard.history or {},
                        tags                  = existingCard and existingCard.tags or {},
                    }
                    
                    WoWStudySaved.decks[deckName].cardsByQuestion[c.question] = card
                end
            end   
        end
    end
end

function WoWStudyFunction.TidyExternalDecks()
    for deckName, deck in pairs(WoWStudySaved.decks) do
        if deck.source == "external" and not _G["deck_" .. deckName] then
            print("Deck " .. deckName .. " no longer exists in the external file. Deleting.")
            WoWStudySaved.decks[deckName] = nil
        end
    end
end

function WoWStudyFunction.TidyExternalDecksCards()
    for deckName, deck in pairs(WoWStudySaved.decks) do
        if deck.source == "external" then
            for question, card in pairs(deck.cardsByQuestion) do
                local found = false
                for i, c in ipairs(_G["deck_" .. deckName]) do
                    if c.question == card.question then
                        found = true
                        break
                    end
                end

                if not found then
                    WoWStudySaved.decks[deckName].cardsByQuestion[card.question] = nil
                end
            end
        end
    end
end

---
-- Initalise Settings
---
function WoWStudyFunction.InitialiseSettings()
    -- Set default settings for the addon
    if WoWStudySaved.settings.enableKills == nil then
        WoWStudySaved.settings.enableKills = true
    end
    if WoWStudySaved.settings.enableQuests == nil then
        WoWStudySaved.settings.enableQuests = true
    end
    if WoWStudySaved.settings.enableOnDeath == nil then
        WoWStudySaved.settings.enableOnDeath = true
    end
    if WoWStudySaved.settings.killInterval == nil then
        WoWStudySaved.settings.killInterval = 1
    end
    if WoWStudySaved.settings.timerValue == nil then
        WoWStudySaved.settings.timerValue = 60
    end
    if WoWStudySaved.settings.gatheringCheck == nil then
        WoWStudySaved.settings.gatheringCheck = true
    end
end

---
-- Update selectedFlashCards global
---
function WoWStudyFunction.UpdateSelectedFlashcards()
    WoWStudyGlobal.selectedFlashcards = {}
    for deckName, deck in pairs(WoWStudySaved.decks) do
        if deck.isSelected then
            for question, card in pairs(deck.cardsByQuestion) do
                table.insert(WoWStudyGlobal.selectedFlashcards, card)
            end
        end
    end
end

---
-- INITIALISE
---
function WoWStudyFunction.Initialise()
    -- Set up saved settings
    WoWStudyFunction.InitialiseSettings()

    -- Load and tidy external cards from files
    WoWStudyFunction.LoadExternalDecks()
    WoWStudyFunction.TidyExternalDecks()
    WoWStudyFunction.TidyExternalDecksCards()

    -- Update selected flashcards
    WoWStudyFunction.UpdateSelectedFlashcards()

    -- Setup Menu Frame
    WoWStudyFunction.InitMenuPanel()
end
