const Controller = require('libflitter/controller/Controller')
const Page = require('../../../models/api/Page.model')
const Node = require('../../../models/api/Node.model')
const FileGroup = require('../../../models/api/FileGroup.model')
const { ObjectId } = require('mongodb')

/*
 * File Controller
 * -------------------------------------------------------------
 * Put some description here!
 */
class File extends Controller {
    static get services() {
        return [...super.services, 'models']
    }

    async create_config(req, res) {
        const { page, node } = req.form

        const group = new FileGroup({
            NodeId: node.UUID,
            PageId: page.UUID,
            FileIds: [],
        })

        if ( req.body.UUID ) {
            const existingUUID = await FileGroup.findOne({ UUID: req.body.UUID })
            if ( !existingUUID ) {
                group.UUID = req.body.UUID
            }
        }

        await group.version_save(`Added to page "${page.Name}"`, req.user.id)
        req.user.allow(`files:${group.UUID}`)
        await req.user.save()

        return res.api(group)
    }

    async get_config(req, res) {
        const { page, node, file_group } = req.form

        const File = this.models.get('upload::File')
        file_group.files = await File.find({_id: {$in: file_group.FileIds.map(x => ObjectId(x))}})

        return res.api(file_group)
    }

    async save_upload(req, res) {
        const { page, node, file_group } = req.form

        const n_files = Object.values(req.uploads).length

        for ( const key in req.uploads ) {
            if ( !req.uploads.hasOwnProperty(key) ) continue
            if ( !key.startsWith('uploaded_file_') ) continue

            file_group.FileIds.push(req.uploads[key].id)
        }

        await file_group.version_save(`Added ${n_files} file${n_files === 1 ? '' : 's'}`, req.user.id)
        return res.api()
    }

    async download(req, res) {
        const { page, node, file_group } = req.form

        if ( !file_group.FileIds.includes(req.params.FileId) ) {
            return req.security.deny()
        }

        const File = this.models.get('upload::File')
        const file = await File.findOne({_id: ObjectId(req.params.FileId)})
        if ( !file ) return res.status(404).api({})

        return file.send(res)
    }

    async delete_group(req, res) {
        const { page, node, file_group } = req.form

        await file_group.delete()
        return res.api({})
    }
}

module.exports = exports = File
