/* ----------------------------------------------------------------------------

 Question Server
 GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>

 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 3 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 <https://www.gnu.org/licenses/>.

 ------------------------------------------------------------------------- */

import logger from '../../../utils/logger'
import utils from '../../../utils/utils'
import type { Request, SubmoduleData, User } from '../../../types/basicTypes'
import type { Response } from 'express'

const quickVoteResultsDir = 'stats/qvote'
const quickVotes = 'stats/qvote/votes.json'
interface QuickVotes {
    voteNames?: string[]
}

interface QuickVote {
    votes: {
        [key: string]: string
    }
    sum: {
        [key: string]: number
    }
}

function setup(data: SubmoduleData): void {
    const { app /* userDB, url, publicdirs, moduleSpecificData */ } = data

    app.get('/quickvote', (req: Request, res: Response) => {
        const key = req.query.key.toString()
        const val: string = req.query.val
        const user: User = req.session.user

        if (!key || !val) {
            res.render('votethank', {
                results: 'error',
                msg: 'no key or val query param!',
            })
            return
        }

        // FIXME: check vote type in file
        let votes: QuickVotes = {}
        if (utils.FileExists(quickVotes)) {
            votes = utils.ReadJSON(quickVotes)
        } else {
            logger.Log(
                `No such vote "${key}", and quickVotes.json is missing ( #${user.id}: ${key}-${val} )`,
                logger.GetColor('blue')
            )
            res.render('votethank', {
                result: 'no such pool',
            })
            return
        }

        if (!votes.voteNames.includes(key)) {
            logger.Log(
                `No such vote "${key}" ( #${user.id}: ${key}-${val} )`,
                logger.GetColor('blue')
            )
            res.render('votethank', {
                result: 'no such pool',
            })
            return
        }

        const voteFile = quickVoteResultsDir + '/' + key + '.json'

        let voteData: QuickVote = {
            votes: {},
            sum: {},
        }

        if (utils.FileExists(voteFile)) {
            voteData = utils.ReadJSON(voteFile)
        } else {
            utils.CreatePath(quickVoteResultsDir)
        }

        const prevVote = voteData.votes[user.id]

        voteData.votes[user.id] = val
        if (voteData.sum[val]) {
            voteData.sum[val]++
        } else {
            voteData.sum[val] = 1
        }
        if (prevVote) {
            if (voteData.sum[prevVote]) {
                voteData.sum[prevVote] -= 1
            }
        }

        logger.Log(
            `Vote from #${user.id}: ${key}: ${val}`,
            logger.GetColor('blue')
        )
        res.render('votethank', {
            result: prevVote ? 'already voted' : 'success',
            prevVote: prevVote,
            msg: 'vote added',
        })

        utils.WriteFile(JSON.stringify(voteData), voteFile)
    })
}

export default {
    setup: setup,
}
