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

 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/>.

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

// package requires
import express, { RequestHandler } from 'express'
import type { Database } from 'better-sqlite3'
const app = express()

// other requires
import utils from '../../utils/utils'
import logger from '../../utils/logger'
import auth from '../../middlewares/auth.middleware'
import { SetupData } from '../../server'
import { ModuleType, Request } from '../../types/basicTypes'

// stuff gotten from server.js
let userDB: Database
let publicdirs: string[] = []
let nextdir = ''

function GetApp(): ModuleType {
    app.use(
        express.urlencoded({
            limit: '5mb',
            extended: true,
        }) as RequestHandler
    )
    app.use(
        express.json({
            limit: '5mb',
        }) as RequestHandler
    )
    app.set('view engine', 'ejs')
    app.set('views', ['./src/modules/dataEditor/views', './src/sharedViews'])
    app.use(
        auth({
            userDB: userDB,
            exceptions: ['/favicon.ico'],
        })
    )
    app.use((req: Request, _res, next) => {
        const url = req.url.split('?')[0]
        if (url.includes('.html') || url === '/') {
            logger.LogReq(req)
        }
        next()
    })
    publicdirs.forEach((pdir) => {
        app.use(express.static(pdir))
    })
    app.use(express.static(nextdir))

    // --------------------------------------------------------------

    function AddHtmlRoutes(files: string[]) {
        const routes = files.reduce((acc, file) => {
            if (file.includes('html')) {
                acc.push(file.split('.')[0])
                return acc
            }
            return acc
        }, [])

        routes.forEach((route) => {
            logger.DebugLog(`Added route /${route}`, 'DataEditor routes', 1)
            app.get(`/${route}`, function (_req: Request, res) {
                res.redirect(`${route}.html`)
            })
        })
    }
    AddHtmlRoutes(utils.ReadDir(nextdir))

    // --------------------------------------------------------------

    app.get('/', function (req: Request, res) {
        res.end('hai')
        logger.LogReq(req)
    })

    return {
        app: app,
    }
}

export default {
    name: 'Data editor',
    getApp: GetApp,
    setup: (data: SetupData): void => {
        userDB = data.userDB
        publicdirs = data.publicdirs
        nextdir = data.nextdir
    },
}
