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

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

        const iot_devices = await db.iot_devices.create(
            {
                id: data.id || undefined,
        
        device_type: data.device_type
        ||
        null
            ,
            
        device_label: data.device_label
        ||
        null
            ,
            
        serial_number: data.serial_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        paired_at: data.paired_at
        ||
        null
            ,
            
        last_seen_at: data.last_seen_at
        ||
        null
            ,
            
        battery_level: data.battery_level
        ||
        null
            ,
            
        firmware_version: data.firmware_version
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return iot_devices;
    }
    

    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_devicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                device_type: item.device_type
            ||
            null
            ,
            
                device_label: item.device_label
            ||
            null
            ,
            
                serial_number: item.serial_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                paired_at: item.paired_at
            ||
            null
            ,
            
                last_seen_at: item.last_seen_at
            ||
            null
            ,
            
                battery_level: item.battery_level
            ||
            null
            ,
            
                firmware_version: item.firmware_version
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return iot_devices;
    }

    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_devices = await db.iot_devices.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.device_type !== undefined) updatePayload.device_type = data.device_type;
        
        
        if (data.device_label !== undefined) updatePayload.device_label = data.device_label;
        
        
        if (data.serial_number !== undefined) updatePayload.serial_number = data.serial_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.paired_at !== undefined) updatePayload.paired_at = data.paired_at;
        
        
        if (data.last_seen_at !== undefined) updatePayload.last_seen_at = data.last_seen_at;
        
        
        if (data.battery_level !== undefined) updatePayload.battery_level = data.battery_level;
        
        
        if (data.firmware_version !== undefined) updatePayload.firmware_version = data.firmware_version;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return iot_devices;
    }

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

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

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


        return iot_devices;
    }

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

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

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

        await iot_devices.destroy({
            transaction
        });

        return iot_devices;
    }

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

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

        if (!iot_devices) {
            return iot_devices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.iot_telemetry_events_device = await iot_devices.getIot_telemetry_events_device({
            transaction
        });
        
        
        
        output.alerts_device = await iot_devices.getAlerts_device({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.patient = await iot_devices.getPatient({
            transaction
        });
        
        
        output.accounts = await iot_devices.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.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.device_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'iot_devices',
                        'device_label',
                        filter.device_label,
                    ),
                };
            }
            
            if (filter.serial_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'iot_devices',
                        'serial_number',
                        filter.serial_number,
                    ),
                };
            }
            
            if (filter.firmware_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'iot_devices',
                        'firmware_version',
                        filter.firmware_version,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    last_seen_at: {
                    ...where.last_seen_at,
                            [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.device_type) {
                where = {
                    ...where,
                device_type: filter.device_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      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_devices.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_devices',
                        'device_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

