const UserError = require('vn-loopback/util/user-error');
const fs = require('fs-extra');
const path = require('path');
const isProduction = require('vn-loopback/server/boot/isProduction');

module.exports = Self => {
    Self.remoteMethod('deleteTrashFiles', {
        description: 'Deletes files that have trash type',
        accessType: 'WRITE',
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/deleteTrashFiles`,
            verb: 'POST'
        }
    });

    Self.deleteTrashFiles = async options => {
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        if (!isProduction())
            throw new UserError(`Action not allowed on the test environment`);

        const models = Self.app.models;
        const DmsContainer = models.DmsContainer;

        const trashDmsType = await models.DmsType.findOne({
            where: {code: 'trash'}
        }, myOptions);

        const date = Date.vnNew();
        date.setMonth(date.getMonth() - 4);

        const dmsToDelete = await models.Dms.find({
            where: {
                and: [
                    {dmsTypeFk: trashDmsType.id},
                    {created: {lt: date}}
                ]
            }
        }, myOptions);

        for (let dms of dmsToDelete) {
            const pathHash = DmsContainer.getHash(dms.id);
            const dmsContainer = await DmsContainer.container(pathHash);
            try {
                const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
                await fs.unlink(dstFile);
            } catch (err) {
                if (err.code != 'ENOENT' && dms.file)
                    throw err;
            }

            await dms.destroy(myOptions);

            const dstFolder = path.join(dmsContainer.client.root, pathHash);
            try {
                await fs.rmdir(dstFolder);
            } catch (err) {
                continue;
            }
        }
    };
};