const LoopBackContext = require('loopback-context');

module.exports = Self => {
    require('../methods/ticket/changeWorker')(Self);
    require('../methods/ticket/getVolume')(Self);
    require('../methods/ticket/getTotalVolume')(Self);
    require('../methods/ticket/summary')(Self);
    require('../methods/ticket/priceDifference')(Self);
    require('../methods/ticket/componentUpdate')(Self);
    require('../methods/ticket/new')(Self);
    require('../methods/ticket/isEditable')(Self);
    require('../methods/ticket/setDeleted')(Self);
    require('../methods/ticket/restore')(Self);
    require('../methods/ticket/getSales')(Self);
    require('../methods/ticket/getSalesPersonMana')(Self);
    require('../methods/ticket/filter')(Self);
    require('../methods/ticket/getPossibleStowaways')(Self);
    require('../methods/ticket/canBeInvoiced')(Self);
    require('../methods/ticket/makeInvoice')(Self);
    require('../methods/ticket/updateEditableTicket')(Self);
    require('../methods/ticket/isEmpty')(Self);
    require('../methods/ticket/updateDiscount')(Self);
    require('../methods/ticket/uploadFile')(Self);
    require('../methods/ticket/addSale')(Self);
    require('../methods/ticket/transferSales')(Self);
    require('../methods/ticket/canHaveStowaway')(Self);
    require('../methods/ticket/recalculateComponents')(Self);
    require('../methods/ticket/deleteStowaway')(Self);
    require('../methods/ticket/sendSms')(Self);
    require('../methods/ticket/isLocked')(Self);
    require('../methods/ticket/freightCost')(Self);
    require('../methods/ticket/getComponentsSum')(Self);

    Self.observe('before save', async function(ctx) {
        const loopBackContext = LoopBackContext.getCurrentContext();
        const httpCtx = loopBackContext.active;

        if (ctx.isNewInstance) return;

        let changes = ctx.data || ctx.instance;

        if (changes.routeFk === null && ctx.currentInstance.routeFk != null) {
            let instance = JSON.parse(JSON.stringify(ctx.currentInstance));
            let userId = httpCtx.accessToken.userId;
            let logRecord = {
                originFk: ctx.currentInstance.routeFk,
                userFk: userId,
                action: 'delete',
                changedModel: 'Route',
                oldInstance: {ticket: instance.id},
                newInstance: null
            };
            await Self.app.models.RouteLog.create(logRecord);
        }
    });
};