
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 Iot_telemetry_eventsDBApi {
    

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

        const iot_telemetry_events = await db.iot_telemetry_events.create(
            {
                id: data.id || undefined,
        
        recorded_at: data.recorded_at
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        speed: data.speed
        ||
        null
            ,
            
        accuracy_meters: data.accuracy_meters
        ||
        null
            ,
            
        battery_level: data.battery_level
        ||
        null
            ,
            
        event_kind: data.event_kind
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await iot_telemetry_events.setDevice( data.device || null, {
            transaction,
        });
        
        await iot_telemetry_events.setPatient( data.patient || null, {
            transaction,
        });
        
        await iot_telemetry_events.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return iot_telemetry_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 iot_telemetry_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                recorded_at: item.recorded_at
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                speed: item.speed
            ||
            null
            ,
            
                accuracy_meters: item.accuracy_meters
            ||
            null
            ,
            
                battery_level: item.battery_level
            ||
            null
            ,
            
                event_kind: item.event_kind
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return iot_telemetry_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.speed !== undefined) updatePayload.speed = data.speed;
        
        
        if (data.accuracy_meters !== undefined) updatePayload.accuracy_meters = data.accuracy_meters;
        
        
        if (data.battery_level !== undefined) updatePayload.battery_level = data.battery_level;
        
        
        if (data.event_kind !== undefined) updatePayload.event_kind = data.event_kind;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.device !== undefined) {
            await iot_telemetry_events.setDevice(
              
              data.device,
              
              { transaction }
            );
        }
        
        if (data.patient !== undefined) {
            await iot_telemetry_events.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await iot_telemetry_events.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return iot_telemetry_events;
    }

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

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

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


        return iot_telemetry_events;
    }

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

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

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

        await iot_telemetry_events.destroy({
            transaction
        });

        return iot_telemetry_events;
    }

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

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

        if (!iot_telemetry_events) {
            return iot_telemetry_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alerts_trigger_event = await iot_telemetry_events.getAlerts_trigger_event({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.device = await iot_telemetry_events.getDevice({
            transaction
        });
        
        
        output.patient = await iot_telemetry_events.getPatient({
            transaction
        });
        
        
        output.accounts = await iot_telemetry_events.getAccounts({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

      {
        model: db.accounts,
        as: 'accounts',
        
      },



    ];

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

            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    recorded_at: {
                    ...where.recorded_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.speedRange) {
                const [start, end] = filter.speedRange;

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

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

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

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

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

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

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

            
            if (filter.event_kind) {
                where = {
                    ...where,
                event_kind: filter.event_kind,
            };
            }
            


      

      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.accountsId;
        }
        

        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.iot_telemetry_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

