module.exports = Self => {
    Self.remoteMethodCtx('createThermograph', {
        description: 'Creates a new thermograph',
        accessType: 'WRITE',
        accepts: [{
            arg: 'thermographId',
            type: 'string',
            description: 'The thermograph id',
            required: true
        },
        {
            arg: 'model',
            type: 'string',
            description: 'The thermograph model',
            required: true
        },
        {
            arg: 'temperatureFk',
            type: 'string',
            description: 'The thermograph temperature',
            required: true
        },
        {
            arg: 'warehouseId',
            type: 'number',
            description: 'The warehouse id',
            required: true
        }],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/createThermograph`,
            verb: 'POST'
        }
    });

    Self.createThermograph = async(ctx, thermographId, model, temperatureFk, warehouseId, options) => {
        const models = Self.app.models;
        let tx;
        const myOptions = {userId: ctx.req.accessToken.userId};
        const date = Date.vnNew();

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

        if (!myOptions.transaction) {
            tx = await Self.beginTransaction({});
            myOptions.transaction = tx;
        }

        try {
            const thermograph = await models.Thermograph.create({
                id: thermographId,
                model: model
            }, myOptions);

            const travelThermograph = await models.TravelThermograph.create({
                thermographFk: thermograph.id,
                warehouseFk: warehouseId,
                temperatureFk: temperatureFk,
                created: date
            }, myOptions);

            if (tx) await tx.commit();

            return travelThermograph;
        } catch (err) {
            if (tx) await tx.rollback();
            throw err;
        }
    };
};