function WoWStudyFunction.EndSession()

    WoWStudyGlobal.currentSession.endTime = time()
    WoWStudyGlobal.currentSession.duration = WoWStudyGlobal.currentSession.endTime - WoWStudyGlobal.currentSession.startTime

    if WoWStudyGlobal.currentSession.totalAnswered > 0 then
        if #WoWStudySaved.sessions > 100 then -- Limit to 100 sessions
            table.remove(WoWStudySaved.sessions, 1)
        end
        table.insert(WoWStudySaved.sessions, WoWStudyGlobal.currentSession)
    end
end

function WoWStudyFunction.RecordAnswer(question, deckName, result)
    local currentTime = time()
    local card = WoWStudySaved.decks[deckName].cardsByQuestion[question]

    -- Increment answered counts
    card.totalAnswered = card.totalAnswered + 1 -- card
    WoWStudyGlobal.currentSession.totalAnswered = WoWStudyGlobal.currentSession.totalAnswered + 1 -- session
    WoWStudySaved.decks[card.deckName].totalAnswered = WoWStudySaved.decks[card.deckName].totalAnswered + 1 -- deck
    WoWStudySaved.userInformation.lifetimeAnswered = WoWStudySaved.userInformation.lifetimeAnswered + 1 -- lifetime

    -- Set last time answered to current time
    card.lastTime = currentTime

    if result == "correct" then
        card.totalCorrect =  card.totalCorrect + 1
        WoWStudyGlobal.currentSession.totalCorrect = WoWStudyGlobal.currentSession.totalCorrect + 1
        WoWStudySaved.decks[card.deckName].totalCorrect = WoWStudySaved.decks[card.deckName].totalCorrect + 1
        WoWStudySaved.userInformation.lifetimeCorrect = WoWStudySaved.userInformation.lifetimeCorrect + 1
        card.spacedRepetitionLevel = (card.spacedRepetitionLevel or 0) + 1
    else
        card.totalIncorrect =  card.totalIncorrect + 1
        WoWStudyGlobal.currentSession.totalIncorrect = WoWStudyGlobal.currentSession.totalIncorrect + 1
        WoWStudySaved.decks[card.deckName].totalIncorrect = WoWStudySaved.decks[card.deckName].totalIncorrect + 1
        WoWStudySaved.userInformation.lifetimeIncorrect = WoWStudySaved.userInformation.lifetimeIncorrect + 1
        card.spacedRepetitionLevel = 0       
    end


    if #card.history > 20 then
        table.remove(card.history, 1)
    end
    -- Add to history
    table.insert(card.history, {
        correct = result == "correct",
        time = currentTime,
    })
end

