const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.remoteMethodCtx('getMailStates', {
        description: 'Get the states of a month about time control mail',
        accessType: 'READ',
        accepts: [{
            arg: 'id',
            type: 'number',
            description: 'The worker id',
            http: {source: 'path'}
        },
        {
            arg: 'month',
            type: 'number',
            description: 'The number of the month'
        },
        {
            arg: 'year',
            type: 'number',
            description: 'The number of the year'
        }],
        returns: [{
            type: ['object'],
            root: true
        }],
        http: {
            path: `/:id/getMailStates`,
            verb: 'GET'
        }
    });

    Self.getMailStates = async(ctx, workerId, options) => {
        const models = Self.app.models;
        const args = ctx.args;
        const myOptions = {};

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

        if (!await models.Worker.isSubordinate(ctx, workerId)) throw new UserError(`You don't have enough privileges`);

        const times = await models.Time.find({
            fields: ['week'],
            where: {
                month: args.month,
                year: args.year
            }
        }, myOptions);

        const weeks = times.map(time => time.week);
        const weekNumbersSet = new Set(weeks);
        const weekNumbers = Array.from(weekNumbersSet);

        const workerTimeControlMails = await models.WorkerTimeControlMail.find({
            where: {
                workerFk: workerId,
                year: args.year,
                week: {inq: weekNumbers}
            }
        }, myOptions);

        return workerTimeControlMails;
    };
};