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

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

        const face_detections = await db.face_detections.create(
            {
                id: data.id || undefined,
        
        bbox_x: data.bbox_x
        ||
        null
            ,
            
        bbox_y: data.bbox_y
        ||
        null
            ,
            
        bbox_width: data.bbox_width
        ||
        null
            ,
            
        bbox_height: data.bbox_height
        ||
        null
            ,
            
        confidence: data.confidence
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await face_detections.setMedia_item( data.media_item || null, {
            transaction,
        });
        
        await face_detections.setAi_model( data.ai_model || null, {
            transaction,
        });
        
        await face_detections.setFace_embedding( data.face_embedding || null, {
            transaction,
        });
        
        await face_detections.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return face_detections;
    }
    

    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 face_detectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bbox_x: item.bbox_x
            ||
            null
            ,
            
                bbox_y: item.bbox_y
            ||
            null
            ,
            
                bbox_width: item.bbox_width
            ||
            null
            ,
            
                bbox_height: item.bbox_height
            ||
            null
            ,
            
                confidence: item.confidence
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return face_detections;
    }

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


        

        const updatePayload = {};
        
        if (data.bbox_x !== undefined) updatePayload.bbox_x = data.bbox_x;
        
        
        if (data.bbox_y !== undefined) updatePayload.bbox_y = data.bbox_y;
        
        
        if (data.bbox_width !== undefined) updatePayload.bbox_width = data.bbox_width;
        
        
        if (data.bbox_height !== undefined) updatePayload.bbox_height = data.bbox_height;
        
        
        if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.media_item !== undefined) {
            await face_detections.setMedia_item(
              
              data.media_item,
              
              { transaction }
            );
        }
        
        if (data.ai_model !== undefined) {
            await face_detections.setAi_model(
              
              data.ai_model,
              
              { transaction }
            );
        }
        
        if (data.face_embedding !== undefined) {
            await face_detections.setFace_embedding(
              
              data.face_embedding,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await face_detections.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return face_detections;
    }

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

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

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


        return face_detections;
    }

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

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

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

        await face_detections.destroy({
            transaction
        });

        return face_detections;
    }

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

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

        if (!face_detections) {
            return face_detections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.face_matches_face_detection = await face_detections.getFace_matches_face_detection({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.media_item = await face_detections.getMedia_item({
            transaction
        });
        
        
        output.ai_model = await face_detections.getAi_model({
            transaction
        });
        
        
        output.face_embedding = await face_detections.getFace_embedding({
            transaction
        });
        
        
        output.organizations = await face_detections.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.media_items,
        as: 'media_item',
        
        where: filter.media_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.ai_embeddings,
        as: 'face_embedding',
        
        where: filter.face_embedding ? {
          [Op.or]: [
            { id: { [Op.in]: filter.face_embedding.split('|').map(term => Utils.uuid(term)) } },
            {
              vector_ref: {
                [Op.or]: filter.face_embedding.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.bbox_xRange) {
                const [start, end] = filter.bbox_xRange;

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

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

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

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

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

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

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

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

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

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

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

            


      

      

      

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

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

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

    
};

