const Agenda = require('agenda');
const mongoose = require('mongoose');
const log = require('loglevel');

const EmployeeCtrl = require('../controllers/employee');
const PosCtrl = require('../controllers/pos');
const PosTransactionCtrl = require('../controllers/pos-transaction');

const jobs = async () => {

    const agenda = new Agenda({mongo: global.mongoConnection, db: {collection: 'agenda'}});

    global.agendaInstance = agenda;

    const employeeCtrl = new EmployeeCtrl();
    const posCtrl = new PosCtrl();
    const posTransactionCtrl = new PosTransactionCtrl();

    agenda.define('employee-logout', async (job) => {
        await employeeCtrl.logoutEndOfWorkHour();
        job.repeatAt('at '+process.env.POS_AUTO_LOGOUT_TIME).save();
    });

    agenda.define('pos-pulse', async (job) => {
        await posCtrl.pulse();
        job.repeatEvery(process.env.POS_HEARTBEAT_INTERVAL+' minutes').save();
    });

    agenda.define('pos-transactions-status', async (job) => {
        setTimeout(async () => {
            await posTransactionCtrl.status();
            await posTransactionCtrl.clean();
        }, 5000);
        job.repeatEvery(process.env.POS_TRANSACTIONS_STATUS_INTERVAL+' minutes').save();
    });

    agenda.define('pos-transactions-send', async (job) => {
        await posTransactionCtrl.send();
        job.repeatEvery(process.env.POS_TRANSACTIONS_SEND_INTERVAL+' minutes').save();
    });

    agenda.define('pos-transactions-clear', async (job) => {
        await posTransactionCtrl.clear();
        job.repeatAt('at 09:00').save();
    });

    agenda.on('ready', async () => {
        await mongoose.connection.collection('agenda').drop();
        await agenda.now('employee-logout');
        await agenda.now('pos-pulse');
        await agenda.now('pos-transactions-status');
        await agenda.now('pos-transactions-send');
        await agenda.now('pos-transactions-clear');
        await agenda.start();
    })
    .on('error', () => {
        log.error('Agenda connection error!');
    });

}

module.exports = jobs;
