/*****************************************************************************\
|                                               ( )_  _                       |
|    _ _    _ __   _ _    __    ___ ___     _ _ | ,_)(_)  ___   ___     _     |
|   ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| |  | |/',__)/' v `\ /'_`\   |
|   | (_) )| |  ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) )  |
|   | ,__/'(_)  `\__,_)`\__  |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/'  |
|   | |                ( )_) |                                                |
|   (_)                 \___/'                                                |
|                                                                             |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved.             |
| Licensed under the AGPL-3.0.                                                |
|                                                                             |
| According to our dual licensing model, this program can be used either      |
| under the terms of the GNU Affero General Public License, version 3,        |
| or under a proprietary license.                                             |
|                                                                             |
| The texts of the GNU Affero General Public License with an additional       |
| permission and of our proprietary license can be found at and               |
| in the LICENSE file you have received along with this program.              |
|                                                                             |
| This program is distributed in the hope that it will be useful,             |
| but WITHOUT ANY WARRANTY, without even the implied warranty of              |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                |
| GNU Affero General Public License for more details.                         |
|                                                                             |
| "General Bots" is a registered trademark of Pragmatismo.io.                 |
| The licensing of the program under the AGPLv3 does not imply a              |
| trademark license. Therefore any rights, title and interest in              |
| our trademarks remain entirely with us.                                     |
|                                                                             |
\*****************************************************************************/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const botlib_1 = require("botlib");
const app_1 = require("../../../src/app");
const pragmatismo_io_framework_1 = require("pragmatismo-io-framework");
const GBVMService_1 = require("../../basic.gblib/services/GBVMService");
const GBModel_1 = require("../../core.gbapp/models/GBModel");
const cron = require('node-cron');
/**
 * @fileoverview Schedule Services.
 */
/**
 * Basic services for BASIC manipulation.
 */
class ScheduleServices extends botlib_1.GBService {
    async deleteScheduleIfAny(min, name) {
        const task = min["scheduleMap"] ? min["scheduleMap"][name] : null;
        if (task) {
            task.destroy();
            delete min["scheduleMap"][name];
        }
        const count = await GBModel_1.GuaribasSchedule.destroy({
            where: {
                instanceId: min.instance.instanceId,
                name: name
            }
        });
        if (count > 0) {
            botlib_1.GBLog.info(`BASIC: Removed ${name} SET SCHEDULE and ${count} rows from storage on: ${min.botId}...`);
        }
    }
    /**
     * Finds and update user agent information to a next available person.
     */
    async createOrUpdateSchedule(min, schedule, name) {
        let record = await GBModel_1.GuaribasSchedule.findOne({
            where: {
                instanceId: min.instance.instanceId,
                name: name
            }
        });
        if (record === null) {
            record = await GBModel_1.GuaribasSchedule.create({
                instanceId: min.instance.instanceId,
                name: name,
                schedule: schedule
            });
        }
        else {
            record.schedule = schedule;
            await record.save();
        }
        this.ScheduleItem(record, min);
        return record;
    }
    /**
   * Load all cached schedule from BASIC SET SCHEDULE keyword.
   */
    async loadSchedules(min) {
        let schedules;
        try {
            const options = { where: { instanceId: min.instance.instanceId } };
            schedules = await GBModel_1.GuaribasSchedule.findAll(options);
            botlib_1.GBLog.info(`Loading schedules for ${min.instance.botId}...`);
            await pragmatismo_io_framework_1.CollectionUtil.asyncForEach(schedules, async (item) => {
                this.ScheduleItem(item, min);
            });
        }
        catch (error) {
            throw new Error(`Cannot schedule: ${error.message}.`);
        }
        return schedules;
    }
    ScheduleItem(item, min) {
        botlib_1.GBLog.info(`Scheduling ${item.name} on ${min.botId}...`);
        try {
            const options = {
                scheduled: true,
                timezone: 'America/Sao_Paulo'
            };
            const task = min["scheduleMap"][item.name];
            if (task) {
                task.stop();
                min["scheduleMap"][item.name] = null;
            }
            min["scheduleMap"][item.name] = cron.schedule(item.schedule, function () {
                const finalData = async () => {
                    let script = item.name;
                    let min = app_1.GBServer.globals.minInstances.filter(p => p.instance.instanceId === item.instanceId)[0];
                    await GBVMService_1.GBVMService.callVM(script, min, null, null);
                };
                (async () => {
                    await finalData();
                })();
            }, options);
            botlib_1.GBLog.info(`Running .gbdialog word ${item.name} on:${item.schedule}...`);
        }
        catch (error) { }
    }
}
exports.ScheduleServices = ScheduleServices;
//# sourceMappingURL=ScheduleServices.js.map