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

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

        const beatmaps = await db.beatmaps.create(
            {
                id: data.id || undefined,
        
        osu_beatmap_numeric: data.osu_beatmap_numeric
        ||
        null
            ,
            
        difficulty_name: data.difficulty_name
        ||
        null
            ,
            
        mode: data.mode
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        playcount: data.playcount
        ||
        null
            ,
            
        passcount: data.passcount
        ||
        null
            ,
            
        star_rating: data.star_rating
        ||
        null
            ,
            
        bpm: data.bpm
        ||
        null
            ,
            
        length_seconds: data.length_seconds
        ||
        null
            ,
            
        cs: data.cs
        ||
        null
            ,
            
        ar: data.ar
        ||
        null
            ,
            
        od: data.od
        ||
        null
            ,
            
        hp: data.hp
        ||
        null
            ,
            
        last_synced_at: data.last_synced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await beatmaps.setBeatmap_set( data.beatmap_set || null, {
            transaction,
        });
        
        await beatmaps.setMapper( data.mapper || null, {
            transaction,
        });
        
        await beatmaps.setArtist( data.artist || null, {
            transaction,
        });
        

        

        

        return beatmaps;
    }
    

    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 beatmapsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                osu_beatmap_numeric: item.osu_beatmap_numeric
            ||
            null
            ,
            
                difficulty_name: item.difficulty_name
            ||
            null
            ,
            
                mode: item.mode
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                playcount: item.playcount
            ||
            null
            ,
            
                passcount: item.passcount
            ||
            null
            ,
            
                star_rating: item.star_rating
            ||
            null
            ,
            
                bpm: item.bpm
            ||
            null
            ,
            
                length_seconds: item.length_seconds
            ||
            null
            ,
            
                cs: item.cs
            ||
            null
            ,
            
                ar: item.ar
            ||
            null
            ,
            
                od: item.od
            ||
            null
            ,
            
                hp: item.hp
            ||
            null
            ,
            
                last_synced_at: item.last_synced_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return beatmaps;
    }

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

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


        

        const updatePayload = {};
        
        if (data.osu_beatmap_numeric !== undefined) updatePayload.osu_beatmap_numeric = data.osu_beatmap_numeric;
        
        
        if (data.difficulty_name !== undefined) updatePayload.difficulty_name = data.difficulty_name;
        
        
        if (data.mode !== undefined) updatePayload.mode = data.mode;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.playcount !== undefined) updatePayload.playcount = data.playcount;
        
        
        if (data.passcount !== undefined) updatePayload.passcount = data.passcount;
        
        
        if (data.star_rating !== undefined) updatePayload.star_rating = data.star_rating;
        
        
        if (data.bpm !== undefined) updatePayload.bpm = data.bpm;
        
        
        if (data.length_seconds !== undefined) updatePayload.length_seconds = data.length_seconds;
        
        
        if (data.cs !== undefined) updatePayload.cs = data.cs;
        
        
        if (data.ar !== undefined) updatePayload.ar = data.ar;
        
        
        if (data.od !== undefined) updatePayload.od = data.od;
        
        
        if (data.hp !== undefined) updatePayload.hp = data.hp;
        
        
        if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.beatmap_set !== undefined) {
            await beatmaps.setBeatmap_set(
              
              data.beatmap_set,
              
              { transaction }
            );
        }
        
        if (data.mapper !== undefined) {
            await beatmaps.setMapper(
              
              data.mapper,
              
              { transaction }
            );
        }
        
        if (data.artist !== undefined) {
            await beatmaps.setArtist(
              
              data.artist,
              
              { transaction }
            );
        }
        

        
        

        

        return beatmaps;
    }

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

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

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


        return beatmaps;
    }

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

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

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

        await beatmaps.destroy({
            transaction
        });

        return beatmaps;
    }

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

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

        if (!beatmaps) {
            return beatmaps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.game_rounds_option_a_beatmap = await beatmaps.getGame_rounds_option_a_beatmap({
            transaction
        });
        
        output.game_rounds_option_b_beatmap = await beatmaps.getGame_rounds_option_b_beatmap({
            transaction
        });
        
        
        
        
        
        
        output.beatmap_set = await beatmaps.getBeatmap_set({
            transaction
        });
        
        
        output.mapper = await beatmaps.getMapper({
            transaction
        });
        
        
        output.artist = await beatmaps.getArtist({
            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.beatmap_sets,
        as: 'beatmap_set',
        
        where: filter.beatmap_set ? {
          [Op.or]: [
            { id: { [Op.in]: filter.beatmap_set.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.beatmap_set.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

