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

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

        const game_rounds = await db.game_rounds.create(
            {
                id: data.id || undefined,
        
        round_number: data.round_number
        ||
        null
            ,
            
        round_mode: data.round_mode
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        time_limit_ms: data.time_limit_ms
        ||
        null
            ,
            
        presented_at: data.presented_at
        ||
        null
            ,
            
        answered_at: data.answered_at
        ||
        null
            ,
            
        player_choice: data.player_choice
        ||
        null
            ,
            
        correct_choice: data.correct_choice
        ||
        null
            ,
            
        is_correct: data.is_correct
        ||
        false
        
            ,
            
        lose_reason: data.lose_reason
        ||
        null
            ,
            
        value_a: data.value_a
        ||
        null
            ,
            
        value_b: data.value_b
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await game_rounds.setSession( data.session || null, {
            transaction,
        });
        
        await game_rounds.setOption_a_beatmap( data.option_a_beatmap || null, {
            transaction,
        });
        
        await game_rounds.setOption_b_beatmap( data.option_b_beatmap || null, {
            transaction,
        });
        

        

        

        return game_rounds;
    }
    

    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 game_roundsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                round_number: item.round_number
            ||
            null
            ,
            
                round_mode: item.round_mode
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                time_limit_ms: item.time_limit_ms
            ||
            null
            ,
            
                presented_at: item.presented_at
            ||
            null
            ,
            
                answered_at: item.answered_at
            ||
            null
            ,
            
                player_choice: item.player_choice
            ||
            null
            ,
            
                correct_choice: item.correct_choice
            ||
            null
            ,
            
                is_correct: item.is_correct
            ||
            false
        
            ,
            
                lose_reason: item.lose_reason
            ||
            null
            ,
            
                value_a: item.value_a
            ||
            null
            ,
            
                value_b: item.value_b
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return game_rounds;
    }

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

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


        

        const updatePayload = {};
        
        if (data.round_number !== undefined) updatePayload.round_number = data.round_number;
        
        
        if (data.round_mode !== undefined) updatePayload.round_mode = data.round_mode;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.time_limit_ms !== undefined) updatePayload.time_limit_ms = data.time_limit_ms;
        
        
        if (data.presented_at !== undefined) updatePayload.presented_at = data.presented_at;
        
        
        if (data.answered_at !== undefined) updatePayload.answered_at = data.answered_at;
        
        
        if (data.player_choice !== undefined) updatePayload.player_choice = data.player_choice;
        
        
        if (data.correct_choice !== undefined) updatePayload.correct_choice = data.correct_choice;
        
        
        if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
        
        
        if (data.lose_reason !== undefined) updatePayload.lose_reason = data.lose_reason;
        
        
        if (data.value_a !== undefined) updatePayload.value_a = data.value_a;
        
        
        if (data.value_b !== undefined) updatePayload.value_b = data.value_b;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.session !== undefined) {
            await game_rounds.setSession(
              
              data.session,
              
              { transaction }
            );
        }
        
        if (data.option_a_beatmap !== undefined) {
            await game_rounds.setOption_a_beatmap(
              
              data.option_a_beatmap,
              
              { transaction }
            );
        }
        
        if (data.option_b_beatmap !== undefined) {
            await game_rounds.setOption_b_beatmap(
              
              data.option_b_beatmap,
              
              { transaction }
            );
        }
        

        
        

        

        return game_rounds;
    }

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

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

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


        return game_rounds;
    }

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

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

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

        await game_rounds.destroy({
            transaction
        });

        return game_rounds;
    }

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

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

        if (!game_rounds) {
            return game_rounds;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.session = await game_rounds.getSession({
            transaction
        });
        
        
        output.option_a_beatmap = await game_rounds.getOption_a_beatmap({
            transaction
        });
        
        
        output.option_b_beatmap = await game_rounds.getOption_b_beatmap({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.round_mode) {
                where = {
                    ...where,
                round_mode: filter.round_mode,
            };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                state: filter.state,
            };
            }
            
            if (filter.player_choice) {
                where = {
                    ...where,
                player_choice: filter.player_choice,
            };
            }
            
            if (filter.correct_choice) {
                where = {
                    ...where,
                correct_choice: filter.correct_choice,
            };
            }
            
            if (filter.is_correct) {
                where = {
                    ...where,
                is_correct: filter.is_correct,
            };
            }
            
            if (filter.lose_reason) {
                where = {
                    ...where,
                lose_reason: filter.lose_reason,
            };
            }
            


      

      

      



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

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

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

    
};

