const Controller = require('libflitter/controller/Controller')
const Codium = require('../../../models/api/Codium.model')

/*
 * FormCode Controller
 * -------------------------------------------------------------
 * Put some description here!
 */
class FormCode extends Controller {

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

        const code = new Codium({
            NodeId: node.UUID,
            PageId: page.UUID,
            code: '',
        })

        if ( req.body.Language ) {
            code.Language = req.body.Language
        }

        if ( req.body.code ) {
            code.code = req.body.code
        }

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

        await code.version_save(`Added to page "${page.Name}"`, req.user.id)
        return res.api(code)
    }

    async get_config(req, res) {
        return res.api(req.form.codium)
    }

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

        codium.code = req.body.code
        codium.Language = req.body.Language
        codium.NodeId = node.UUID
        codium.PageId = page.UUID
        await codium.version_save(`Updated in page "${page.Name}"`, req.user.id)
        return res.api(codium)
    }

    async drop_code(req, res) {
        const { codium } = req.form

        codium.Active = false
        await codium.version_save(`Deleted`, req.user.id)
        return res.api({})
    }
}

module.exports = exports = FormCode
