import {OnWorkerEvent, Processor, WorkerHost} from "@nestjs/bullmq";
import {Job} from "bullmq";
import {Logger} from "@nestjs/common";
import {XTiktokDownloadService} from "./x-tiktok.download.service";
import {InjectBot} from "nestjs-telegraf";
import {Context, Telegraf} from "telegraf";
import {map} from "lodash";
import {_sleep} from "../../shared/helper";
import fs from "fs";


@Processor('download_video_queue')
export class VideoDownloadProcessor extends WorkerHost {
    private readonly logger = new Logger("VideoDownloadProcessor");
    private adminChatId = process.env.TELEGRAM_ADMIN_ID || 0;

    constructor(
        private downloadTool: XTiktokDownloadService,
        @InjectBot() private readonly bot: Telegraf<Context>,
    ) {
        super();
    }

    async process(job: Job, token: string | undefined): Promise<any> {

        console.log(`VideoDownloadProcessor ==> process => ${job.name}`);
        console.log('job_data', job.data);

        let {telegramChatId, url, sourceType, urls} = job.data;
        const jobName = job.name;

        switch (jobName) {
            case 'download': {
                const result = await this.downloadTool.download(url);
                console.log('telegramChatId:', telegramChatId);
                if (result.status === 0) {
                    //error
                    await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                        `Có lỗi.`,
                    );
                    return;
                }
                await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                    `đã download xong: ${result.title}`,
                );

                return {
                    status: 1,
                    filePath: result.filePath,
                    title: result.title,
                    telegramChatId,
                    jobName,
                    originalUrl: url,
                };
            }
            case 'download_multi': {
                const totalLink = urls.length;
                let done = 0;
                for (const url of urls) {
                    await _sleep(1000);
                    console.log(`Downloading ${url}`);
                    const result = await this.downloadTool.download(url).catch((err) => {
                        console.log(err);
                        return {
                            status: 0,
                            error: err.message,
                            filePath: '',
                            title: '',
                        }
                    });
                    if (result.status === 0) {
                        //error
                        await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                            `Có lỗi. ${result.error}`,
                        );
                        return;
                    } else {
                        done++;
                        await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                            `đã download xong ${done}/${totalLink}: ${result.title}`,
                        );
                        await this.sendVideoToTelegram(telegramChatId || this.adminChatId, result.filePath, result.title);
                    }
                    // // Dừng lại đợi ở đây
                    // results.push(data);
                }
                // map(urls, async (url) => {
                //
                //
                //
                //     return {
                //         status: 1,
                //         filePath: result.filePath,
                //         title: result.title,
                //         telegramChatId,
                //         jobName,
                //         originalUrl: url,
                //     };
                // })

            }
            case 'download_tiktok': {
                const result = await this.downloadTool.downloadTikTok(url);
                console.log({result});
                console.log('telegramChatId:', telegramChatId);
                await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                    `đã download xong: ${result.title}`,
                );

                return {
                    status: 1,
                    filePath: result.filePath,
                    title: result.title,
                    telegramChatId,
                    jobName,
                    originalUrl: url,
                };
            }
            case 'youtube': {
                break;
            }
            case 'facebook_reels': {
                const result = await this.downloadTool.downloadFacebookReels(url);
                console.log({result});
                console.log('telegramChatId:', telegramChatId);
                await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                    `đã download xong: ${result.title}`,
                );

                return {
                    status: 1,
                    filePath: result.filePath,
                    title: result.title,
                    telegramChatId,
                    jobName,
                    originalUrl: url,
                };
            }
            case 'mp4url': {
                const result = await this.downloadTool.downloadUrlMp4(url, sourceType);
                console.log({result});
                console.log('telegramChatId:', telegramChatId);
                await this.bot.telegram.sendMessage(telegramChatId > 0 ? telegramChatId : this.adminChatId,
                    `đã download xong: ${result.title}`,
                );

                return {
                    status: 1,
                    filePath: result.filePath,
                    title: result.title,
                    telegramChatId,
                    jobName,
                    originalUrl: url,
                };
            }
        }

        return Promise.resolve({
            status: 0,
            telegramChatId,
            filePath: '',
            title: '',
            jobName,
            originalUrl: url,
        });
    }

    @OnWorkerEvent('completed')
    async onCompleted(job: Job<any>) {
        console.log('VideoDownloadProcessor_completed');
        const adminChatId = process.env.TELEGRAM_ADMIN_ID || 0;
        const status = job.returnvalue.status;
        const telegramChatId = job.returnvalue.telegramChatId;
        const originalUrl = job.returnvalue.originalUrl;
        if (status === 0) {
            //const topic = job.returnvalue.topic;
            await this.bot.telegram.sendMessage(telegramChatId || adminChatId, `Lỗi download: ${originalUrl}`);
        } else {
            const filePath = job.returnvalue.filePath;
            const title = job.returnvalue.title;
            await this.sendVideoToTelegram(telegramChatId || adminChatId, filePath, title);
        }
    }


    async sendVideoToTelegram(chatId, filePath, caption = '') {
        await this.bot.telegram.sendMessage(chatId, 'chờ gửi lên telegram ...')
        await this.bot.telegram.sendVideo(chatId, {source: filePath}, {caption});
        // Xoá file sau khi gửi
        return fs.unlinkSync(filePath);
    }


}
