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

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

        const flowsheet_nodes = await db.flowsheet_nodes.create(
            {
                id: data.id || undefined,
        
        node_key: data.node_key
        ||
        null
            ,
            
        node_type: data.node_type
        ||
        null
            ,
            
        unit_operation: data.unit_operation
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        position_x: data.position_x
        ||
        null
            ,
            
        position_y: data.position_y
        ||
        null
            ,
            
        parameters_json: data.parameters_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await flowsheet_nodes.setFlowsheet( data.flowsheet || null, {
            transaction,
        });
        
        await flowsheet_nodes.setEquipment_item( data.equipment_item || null, {
            transaction,
        });
        
        await flowsheet_nodes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await flowsheet_nodes.setTest_basis(data.test_basis || [], {
            transaction,
        });
        

        

        return flowsheet_nodes;
    }
    

    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 flowsheet_nodesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                node_key: item.node_key
            ||
            null
            ,
            
                node_type: item.node_type
            ||
            null
            ,
            
                unit_operation: item.unit_operation
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                position_x: item.position_x
            ||
            null
            ,
            
                position_y: item.position_y
            ||
            null
            ,
            
                parameters_json: item.parameters_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return flowsheet_nodes;
    }

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


        

        const updatePayload = {};
        
        if (data.node_key !== undefined) updatePayload.node_key = data.node_key;
        
        
        if (data.node_type !== undefined) updatePayload.node_type = data.node_type;
        
        
        if (data.unit_operation !== undefined) updatePayload.unit_operation = data.unit_operation;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.position_x !== undefined) updatePayload.position_x = data.position_x;
        
        
        if (data.position_y !== undefined) updatePayload.position_y = data.position_y;
        
        
        if (data.parameters_json !== undefined) updatePayload.parameters_json = data.parameters_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.flowsheet !== undefined) {
            await flowsheet_nodes.setFlowsheet(
              
              data.flowsheet,
              
              { transaction }
            );
        }
        
        if (data.equipment_item !== undefined) {
            await flowsheet_nodes.setEquipment_item(
              
              data.equipment_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await flowsheet_nodes.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.test_basis !== undefined) {
            await flowsheet_nodes.setTest_basis(data.test_basis, { transaction });
        }
        

        

        return flowsheet_nodes;
    }

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

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

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


        return flowsheet_nodes;
    }

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

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

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

        await flowsheet_nodes.destroy({
            transaction
        });

        return flowsheet_nodes;
    }

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

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

        if (!flowsheet_nodes) {
            return flowsheet_nodes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.flowsheet_streams_source_node = await flowsheet_nodes.getFlowsheet_streams_source_node({
            transaction
        });
        
        output.flowsheet_streams_target_node = await flowsheet_nodes.getFlowsheet_streams_target_node({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.flowsheet = await flowsheet_nodes.getFlowsheet({
            transaction
        });
        
        
        output.equipment_item = await flowsheet_nodes.getEquipment_item({
            transaction
        });
        
        
        output.test_basis = await flowsheet_nodes.getTest_basis({
            transaction
        });
        
        
        output.organizations = await flowsheet_nodes.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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


      {
        model: db.metallurgical_tests,
        as: 'test_basis',
        required: false,
      },


    ];

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

            
            if (filter.node_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flowsheet_nodes',
                        'node_key',
                        filter.node_key,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flowsheet_nodes',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.parameters_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flowsheet_nodes',
                        'parameters_json',
                        filter.parameters_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

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

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


      if (filter.test_basis) {
        const searchTerms = filter.test_basis.split('|');

        include = [
          {
            model: db.metallurgical_tests,
            as: 'test_basis_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  lab_reference: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.organizationsId;
        }
        

        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.flowsheet_nodes.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(
                        'flowsheet_nodes',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

