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

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

        const tracks = await db.tracks.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        track_number: data.track_number
        ||
        null
            ,
            
        version: data.version
        ||
        null
            ,
            
        isrc_code: data.isrc_code
        ||
        null
            ,
            
        isrc_source: data.isrc_source
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        sample_rate_hz: data.sample_rate_hz
        ||
        null
            ,
            
        bitrate_kbps: data.bitrate_kbps
        ||
        null
            ,
            
        audio_format: data.audio_format
        ||
        null
            ,
            
        explicit_content: data.explicit_content
        ||
        false
        
            ,
            
        lyrics: data.lyrics
        ||
        null
            ,
            
        audio_fingerprint: data.audio_fingerprint
        ||
        null
            ,
            
        quality_status: data.quality_status
        ||
        null
            ,
            
        quality_notes: data.quality_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tracks.setRelease( data.release || null, {
            transaction,
        });
        
        await tracks.setGenre( data.genre || null, {
            transaction,
        });
        
        await tracks.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tracks.getTableName(),
                belongsToColumn: 'audio_file',
                belongsToId: tracks.id,
            },
            data.audio_file,
            options,
        );
        

        return tracks;
    }
    

    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 tracksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                track_number: item.track_number
            ||
            null
            ,
            
                version: item.version
            ||
            null
            ,
            
                isrc_code: item.isrc_code
            ||
            null
            ,
            
                isrc_source: item.isrc_source
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                sample_rate_hz: item.sample_rate_hz
            ||
            null
            ,
            
                bitrate_kbps: item.bitrate_kbps
            ||
            null
            ,
            
                audio_format: item.audio_format
            ||
            null
            ,
            
                explicit_content: item.explicit_content
            ||
            false
        
            ,
            
                lyrics: item.lyrics
            ||
            null
            ,
            
                audio_fingerprint: item.audio_fingerprint
            ||
            null
            ,
            
                quality_status: item.quality_status
            ||
            null
            ,
            
                quality_notes: item.quality_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < tracks.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.tracks.getTableName(),
                    belongsToColumn: 'audio_file',
                    belongsToId: tracks[i].id,
                },
                data[i].audio_file,
                options,
            );
        }
        

        return tracks;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.track_number !== undefined) updatePayload.track_number = data.track_number;
        
        
        if (data.version !== undefined) updatePayload.version = data.version;
        
        
        if (data.isrc_code !== undefined) updatePayload.isrc_code = data.isrc_code;
        
        
        if (data.isrc_source !== undefined) updatePayload.isrc_source = data.isrc_source;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.sample_rate_hz !== undefined) updatePayload.sample_rate_hz = data.sample_rate_hz;
        
        
        if (data.bitrate_kbps !== undefined) updatePayload.bitrate_kbps = data.bitrate_kbps;
        
        
        if (data.audio_format !== undefined) updatePayload.audio_format = data.audio_format;
        
        
        if (data.explicit_content !== undefined) updatePayload.explicit_content = data.explicit_content;
        
        
        if (data.lyrics !== undefined) updatePayload.lyrics = data.lyrics;
        
        
        if (data.audio_fingerprint !== undefined) updatePayload.audio_fingerprint = data.audio_fingerprint;
        
        
        if (data.quality_status !== undefined) updatePayload.quality_status = data.quality_status;
        
        
        if (data.quality_notes !== undefined) updatePayload.quality_notes = data.quality_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.release !== undefined) {
            await tracks.setRelease(
              
              data.release,
              
              { transaction }
            );
        }
        
        if (data.genre !== undefined) {
            await tracks.setGenre(
              
              data.genre,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tracks.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tracks.getTableName(),
                belongsToColumn: 'audio_file',
                belongsToId: tracks.id,
            },
            data.audio_file,
            options,
        );
        

        return tracks;
    }

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

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

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


        return tracks;
    }

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

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

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

        await tracks.destroy({
            transaction
        });

        return tracks;
    }

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

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

        if (!tracks) {
            return tracks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.track_contributors_track = await tracks.getTrack_contributors_track({
            transaction
        });
        
        
        
        
        
        
        
        output.pitch_requests_track = await tracks.getPitch_requests_track({
            transaction
        });
        
        
        output.playlist_placements_track = await tracks.getPlaylist_placements_track({
            transaction
        });
        
        
        
        output.royalty_lines_track = await tracks.getRoyalty_lines_track({
            transaction
        });
        
        
        
        
        
        
        
        output.analytics_daily_track = await tracks.getAnalytics_daily_track({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.release = await tracks.getRelease({
            transaction
        });
        
        
        output.genre = await tracks.getGenre({
            transaction
        });
        
        
        output.audio_file = await tracks.getAudio_file({
            transaction
        });
        
        
        output.organizations = await tracks.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.releases,
        as: 'release',
        
        where: filter.release ? {
          [Op.or]: [
            { id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



      {
        model: db.file,
        as: 'audio_file',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'version',
                        filter.version,
                    ),
                };
            }
            
            if (filter.isrc_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'isrc_code',
                        filter.isrc_code,
                    ),
                };
            }
            
            if (filter.lyrics) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'lyrics',
                        filter.lyrics,
                    ),
                };
            }
            
            if (filter.audio_fingerprint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'audio_fingerprint',
                        filter.audio_fingerprint,
                    ),
                };
            }
            
            if (filter.quality_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tracks',
                        'quality_notes',
                        filter.quality_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.isrc_source) {
                where = {
                    ...where,
                isrc_source: filter.isrc_source,
            };
            }
            
            if (filter.audio_format) {
                where = {
                    ...where,
                audio_format: filter.audio_format,
            };
            }
            
            if (filter.explicit_content) {
                where = {
                    ...where,
                explicit_content: filter.explicit_content,
            };
            }
            
            if (filter.quality_status) {
                where = {
                    ...where,
                quality_status: filter.quality_status,
            };
            }
            


      

      

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

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

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

    
};

