
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Truck_tracking_eventsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const truck_tracking_events = await db.truck_tracking_events.create(
            {
                id: data.id || undefined,
        
        event_at: data.event_at
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        speed_kph: data.speed_kph
        ||
        null
            ,
            
        heading: data.heading
        ||
        null
            ,
            
        event_note: data.event_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await truck_tracking_events.setTruck( data.truck || null, {
            transaction,
        });
        
        await truck_tracking_events.setMedicine_dispatch( data.medicine_dispatch || null, {
            transaction,
        });
        

        

        

        return truck_tracking_events;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const truck_tracking_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_at: item.event_at
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                speed_kph: item.speed_kph
            ||
            null
            ,
            
                heading: item.heading
            ||
            null
            ,
            
                event_note: item.event_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const truck_tracking_events = await db.truck_tracking_events.bulkCreate(truck_tracking_eventsData, { transaction });

        // For each item created, replace relation files
        

        return truck_tracking_events;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const truck_tracking_events = await db.truck_tracking_events.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.speed_kph !== undefined) updatePayload.speed_kph = data.speed_kph;
        
        
        if (data.heading !== undefined) updatePayload.heading = data.heading;
        
        
        if (data.event_note !== undefined) updatePayload.event_note = data.event_note;
        
        
        updatePayload.updatedById = currentUser.id;

        await truck_tracking_events.update(updatePayload, {transaction});

        
        
        if (data.truck !== undefined) {
            await truck_tracking_events.setTruck(
              
              data.truck,
              
              { transaction }
            );
        }
        
        if (data.medicine_dispatch !== undefined) {
            await truck_tracking_events.setMedicine_dispatch(
              
              data.medicine_dispatch,
              
              { transaction }
            );
        }
        

        
        

        

        return truck_tracking_events;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const truck_tracking_events = await db.truck_tracking_events.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of truck_tracking_events) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of truck_tracking_events) {
                await record.destroy({transaction});
            }
        });


        return truck_tracking_events;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const truck_tracking_events = await db.truck_tracking_events.findByPk(id, options);

        await truck_tracking_events.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await truck_tracking_events.destroy({
            transaction
        });

        return truck_tracking_events;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const truck_tracking_events = await db.truck_tracking_events.findOne(
            { where },
            { transaction },
        );

        if (!truck_tracking_events) {
            return truck_tracking_events;
        }

        const output = truck_tracking_events.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.truck = await truck_tracking_events.getTruck({
            transaction
        });
        
        
        output.medicine_dispatch = await truck_tracking_events.getMedicine_dispatch({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.trucks,
        as: 'truck',
        
        where: filter.truck ? {
          [Op.or]: [
            { id: { [Op.in]: filter.truck.split('|').map(term => Utils.uuid(term)) } },
            {
              truck_code: {
                [Op.or]: filter.truck.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.medicine_dispatches,
        as: 'medicine_dispatch',
        
        where: filter.medicine_dispatch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.medicine_dispatch.split('|').map(term => Utils.uuid(term)) } },
            {
              tracking_reference: {
                [Op.or]: filter.medicine_dispatch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.heading) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'truck_tracking_events',
                        'heading',
                        filter.heading,
                    ),
                };
            }
            
            if (filter.event_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'truck_tracking_events',
                        'event_note',
                        filter.event_note,
                    ),
                };
            }
            

            
            

            
            if (filter.event_atRange) {
                const [start, end] = filter.event_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    event_at: {
                    ...where.event_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    event_at: {
                    ...where.event_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.latitudeRange) {
                const [start, end] = filter.latitudeRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    latitude: {
                    ...where.latitude,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    latitude: {
                    ...where.latitude,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.longitudeRange) {
                const [start, end] = filter.longitudeRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    longitude: {
                    ...where.longitude,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    longitude: {
                    ...where.longitude,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.speed_kphRange) {
                const [start, end] = filter.speed_kphRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    speed_kph: {
                    ...where.speed_kph,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    speed_kph: {
                    ...where.speed_kph,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.truck_tracking_events.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'truck_tracking_events',
                        'event_note',
                        query,
                    ),
                ],
            };
        }

        const records = await db.truck_tracking_events.findAll({
            attributes: [ 'id', 'event_note' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['event_note', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.event_note,
        }));
    }

    
};

