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

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

        const flowsheet_streams = await db.flowsheet_streams.create(
            {
                id: data.id || undefined,
        
        stream_type: data.stream_type
        ||
        null
            ,
            
        mass_flow_tph: data.mass_flow_tph
        ||
        null
            ,
            
        water_flow_m3h: data.water_flow_m3h
        ||
        null
            ,
            
        solids_pct: data.solids_pct
        ||
        null
            ,
            
        au_grade_gpt: data.au_grade_gpt
        ||
        null
            ,
            
        au_recovery_pct: data.au_recovery_pct
        ||
        null
            ,
            
        components_json: data.components_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await flowsheet_streams.setFlowsheet( data.flowsheet || null, {
            transaction,
        });
        
        await flowsheet_streams.setSource_node( data.source_node || null, {
            transaction,
        });
        
        await flowsheet_streams.setTarget_node( data.target_node || null, {
            transaction,
        });
        
        await flowsheet_streams.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return flowsheet_streams;
    }
    

    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_streamsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                stream_type: item.stream_type
            ||
            null
            ,
            
                mass_flow_tph: item.mass_flow_tph
            ||
            null
            ,
            
                water_flow_m3h: item.water_flow_m3h
            ||
            null
            ,
            
                solids_pct: item.solids_pct
            ||
            null
            ,
            
                au_grade_gpt: item.au_grade_gpt
            ||
            null
            ,
            
                au_recovery_pct: item.au_recovery_pct
            ||
            null
            ,
            
                components_json: item.components_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return flowsheet_streams;
    }

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


        

        const updatePayload = {};
        
        if (data.stream_type !== undefined) updatePayload.stream_type = data.stream_type;
        
        
        if (data.mass_flow_tph !== undefined) updatePayload.mass_flow_tph = data.mass_flow_tph;
        
        
        if (data.water_flow_m3h !== undefined) updatePayload.water_flow_m3h = data.water_flow_m3h;
        
        
        if (data.solids_pct !== undefined) updatePayload.solids_pct = data.solids_pct;
        
        
        if (data.au_grade_gpt !== undefined) updatePayload.au_grade_gpt = data.au_grade_gpt;
        
        
        if (data.au_recovery_pct !== undefined) updatePayload.au_recovery_pct = data.au_recovery_pct;
        
        
        if (data.components_json !== undefined) updatePayload.components_json = data.components_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.flowsheet !== undefined) {
            await flowsheet_streams.setFlowsheet(
              
              data.flowsheet,
              
              { transaction }
            );
        }
        
        if (data.source_node !== undefined) {
            await flowsheet_streams.setSource_node(
              
              data.source_node,
              
              { transaction }
            );
        }
        
        if (data.target_node !== undefined) {
            await flowsheet_streams.setTarget_node(
              
              data.target_node,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await flowsheet_streams.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return flowsheet_streams;
    }

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

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

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


        return flowsheet_streams;
    }

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

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

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

        await flowsheet_streams.destroy({
            transaction
        });

        return flowsheet_streams;
    }

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

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

        if (!flowsheet_streams) {
            return flowsheet_streams;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.flowsheet = await flowsheet_streams.getFlowsheet({
            transaction
        });
        
        
        output.source_node = await flowsheet_streams.getSource_node({
            transaction
        });
        
        
        output.target_node = await flowsheet_streams.getTarget_node({
            transaction
        });
        
        
        output.organizations = await flowsheet_streams.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.flowsheet_nodes,
        as: 'source_node',
        
        where: filter.source_node ? {
          [Op.or]: [
            { id: { [Op.in]: filter.source_node.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.source_node.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.components_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flowsheet_streams',
                        'components_json',
                        filter.components_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

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

        where = {
          ...where,
          organizationsId: {[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.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_streams.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_streams',
                        'stream_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

