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

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

        const observation_events = await db.observation_events.create(
            {
                id: data.id || undefined,
        
        observed_at: data.observed_at
        ||
        null
            ,
            
        event_type: data.event_type
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await observation_events.setTrial( data.trial || null, {
            transaction,
        });
        
        await observation_events.setTrial_site( data.trial_site || null, {
            transaction,
        });
        
        await observation_events.setPlot( data.plot || null, {
            transaction,
        });
        
        await observation_events.setPlant( data.plant || null, {
            transaction,
        });
        
        await observation_events.setObserver( data.observer || null, {
            transaction,
        });
        
        await observation_events.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await observation_events.setObservations(data.observations || [], {
            transaction,
        });
        
        await observation_events.setMedia_assets(data.media_assets || [], {
            transaction,
        });
        

        

        return observation_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 observation_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                observed_at: item.observed_at
            ||
            null
            ,
            
                event_type: item.event_type
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.observed_at !== undefined) updatePayload.observed_at = data.observed_at;
        
        
        if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trial !== undefined) {
            await observation_events.setTrial(
              
              data.trial,
              
              { transaction }
            );
        }
        
        if (data.trial_site !== undefined) {
            await observation_events.setTrial_site(
              
              data.trial_site,
              
              { transaction }
            );
        }
        
        if (data.plot !== undefined) {
            await observation_events.setPlot(
              
              data.plot,
              
              { transaction }
            );
        }
        
        if (data.plant !== undefined) {
            await observation_events.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.observer !== undefined) {
            await observation_events.setObserver(
              
              data.observer,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await observation_events.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.observations !== undefined) {
            await observation_events.setObservations(data.observations, { transaction });
        }
        
        if (data.media_assets !== undefined) {
            await observation_events.setMedia_assets(data.media_assets, { transaction });
        }
        

        

        return observation_events;
    }

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

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

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


        return observation_events;
    }

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

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

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

        await observation_events.destroy({
            transaction
        });

        return observation_events;
    }

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

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

        if (!observation_events) {
            return observation_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.observations_observation_event = await observation_events.getObservations_observation_event({
            transaction
        });
        
        
        
        
        
        
        
        output.trial = await observation_events.getTrial({
            transaction
        });
        
        
        output.trial_site = await observation_events.getTrial_site({
            transaction
        });
        
        
        output.plot = await observation_events.getPlot({
            transaction
        });
        
        
        output.plant = await observation_events.getPlant({
            transaction
        });
        
        
        output.observer = await observation_events.getObserver({
            transaction
        });
        
        
        output.observations = await observation_events.getObservations({
            transaction
        });
        
        
        output.media_assets = await observation_events.getMedia_assets({
            transaction
        });
        
        
        output.organizations = await observation_events.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.trials,
        as: 'trial',
        
        where: filter.trial ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trial.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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


      {
        model: db.observations,
        as: 'observations',
        required: false,
      },

      {
        model: db.media_assets,
        as: 'media_assets',
        required: false,
      },


    ];

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

            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'observation_events',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'observation_events',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            observed_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    observed_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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


      

      

      

      

      

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

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


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

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

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

        include = [
          {
            model: db.media_assets,
            as: 'media_assets_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  caption: {
                    [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.observation_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(
                        'observation_events',
                        'summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

