
const db = require('../models');
const Utils = require('../utils');
const {
  getRuntimeEnvironment,
  getRuntimeProjectSlug,
} = require('./runtime-context');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Page_elementsDBApi {
    

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

        const page_elements = await db.page_elements.create(
            {
                id: data.id || undefined,
        
        element_type: data.element_type ?? null,
            
        name: data.name ?? null,
            
        sort_order: data.sort_order ?? 0,
            
        is_visible: data.is_visible ?? false,
            
        x_percent: data.x_percent ?? null,
            
        y_percent: data.y_percent ?? null,
            
        width_percent: data.width_percent ?? null,
            
        height_percent: data.height_percent ?? null,
            
        rotation_deg: data.rotation_deg ?? null,
            
        style_json: data.style_json ?? null,
            
        content_json: data.content_json ?? null,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await page_elements.setPage( data.page || null, {
            transaction,
        });
        

        

        

        return page_elements;
    }
    

    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 page_elementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                element_type: item.element_type ?? null,
            
                name: item.name ?? null,
            
                sort_order: item.sort_order ?? 0,
            
                is_visible: item.is_visible ?? false,
            
                x_percent: item.x_percent ?? null,
            
                y_percent: item.y_percent ?? null,
            
                width_percent: item.width_percent ?? null,
            
                height_percent: item.height_percent ?? null,
            
                rotation_deg: item.rotation_deg ?? null,
            
                style_json: item.style_json ?? null,
            
                content_json: item.content_json ?? null,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return page_elements;
    }

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

        const page_elements = await db.page_elements.findByPk(id, {transaction});


        

        const updatePayload = {};
        
        if (data.element_type !== undefined) updatePayload.element_type = data.element_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_visible !== undefined) updatePayload.is_visible = data.is_visible;
        
        
        if (data.x_percent !== undefined) updatePayload.x_percent = data.x_percent;
        
        
        if (data.y_percent !== undefined) updatePayload.y_percent = data.y_percent;
        
        
        if (data.width_percent !== undefined) updatePayload.width_percent = data.width_percent;
        
        
        if (data.height_percent !== undefined) updatePayload.height_percent = data.height_percent;
        
        
        if (data.rotation_deg !== undefined) updatePayload.rotation_deg = data.rotation_deg;
        
        
        if (data.style_json !== undefined) updatePayload.style_json = data.style_json;
        
        
        if (data.content_json !== undefined) updatePayload.content_json = data.content_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.page !== undefined) {
            await page_elements.setPage(
              
              data.page,
              
              { transaction }
            );
        }
        

        
        

        

        return page_elements;
    }

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

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

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


        return page_elements;
    }

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

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

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

        await page_elements.destroy({
            transaction
        });

        return page_elements;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);
        const pageInclude = {
            model: db.tour_pages,
            as: 'page',
            required: Boolean(runtimeEnvironment || runtimeProjectSlug),
            where: runtimeEnvironment ? { environment: runtimeEnvironment } : {},
            include: runtimeProjectSlug
                ? [{
                    model: db.projects,
                    as: 'project',
                    required: true,
                    where: { slug: runtimeProjectSlug },
                }]
                : [],
        };

        const page_elements = await db.page_elements.findOne(
            { where, include: [pageInclude], transaction },
        );

        if (!page_elements) {
            return page_elements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.page = await page_elements.getPage({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        filter = filter || {};
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

    let include = [

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



    ];
        const runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);

        if (runtimeEnvironment) {
            include[0].where = {
                ...(include[0].where || {}),
                environment: runtimeEnvironment,
            };
            include[0].required = true;
        }

        if (runtimeProjectSlug) {
            include[0].include = [{
                model: db.projects,
                as: 'project',
                required: true,
                where: { slug: runtimeProjectSlug },
            }];
            include[0].required = true;
        }

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'page_elements',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.style_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'page_elements',
                        'style_json',
                        filter.style_json,
                    ),
                };
            }
            
            if (filter.content_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'page_elements',
                        'content_json',
                        filter.content_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.page_elements.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'page_elements',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.page_elements.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,
        }));
    }

    
};
