
const UtilPackage = require('../utils/UtilPackage');
const UtilHttpStatus = require('../../shared/utils/UtilHttpStatus');
const path = require('path');

const packageExport = (req, res) => {
    let userId = req.user ? req.user.documentId : null;
    let documentId = req.params.id;

    UtilPackage.exportPackage(documentId, userId).then(packagePath => {
        res.setHeader('Content-Type', 'application/zip');
        res.sendFile(path.resolve(`${process.cwd()}/${packagePath}.zip`));
    }).catch(err => {
        logger.error(err.message);
        res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
    });
};

const packageImport = (req, res) => {
    if (req.files) {
        let file = req.files.file;
        let fileName = file.originalFilename.toLowerCase();
        let userId = req.user ? req.user.documentId : null;

        if (!fileName.endsWith(".zip") && !fileName.endsWith(".7z")) {
            let message = "Package file type not allowed.";
            logger.error('Error in file upload: ' + message);
            res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send(message);
        } else {
            UtilPackage.importPackage(file, userId).then(result => {
                res.status(UtilHttpStatus.OK).send(result);
            }).catch(error => {
                res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send(error);
            });
        }
    } else {
        res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send('No package file uploaded.');
    }
};

const packageCleanUp = (req, res) => {
    let userId = req.user ? req.user.documentId : null;

    let type = req.params.type;
    let documentId = req.params.id;

    UtilPackage.deletePackage(type, documentId, userId).then(result => {
        res.status(UtilHttpStatus.OK).send(result);
    }).catch(err => {
        res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send(error);
    });
};

module.exports = {
    packageExport,
    packageImport,
    packageCleanUp
};