"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var TaskService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskService = void 0;
const common_1 = require("@nestjs/common");
const schedule_1 = require("@nestjs/schedule");
const sequelize_1 = require("@nestjs/sequelize");
const sequelize_2 = require("sequelize");
const puppeteer_1 = require("puppeteer");
const event_entity_1 = require("./events/entities/event.entity");
let TaskService = TaskService_1 = class TaskService {
    constructor(eventModel) {
        this.eventModel = eventModel;
        this.logger = new common_1.Logger(TaskService_1.name);
        this.to_slug = (text) => {
            return text
                .toLowerCase()
                .trim()
                .replace(/[^\w\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-');
        };
    }
    async handleCron() {
        this.logger.debug('---Cron Start---');
        const browser = await puppeteer_1.default.launch();
        const page = await browser.newPage();
        const url = 'https://champdarts.com/us-darts-masters/';
        const viewport = { width: 1080, height: 1024 };
        await page.goto(url);
        await page.setViewport(viewport);
        const images = await page.evaluate(() => {
            const images = document.querySelectorAll('#av_section_1 .avia_image');
            return Array.from(images).map(img => img['src']);
        });
        const headings = await page.evaluate(() => {
            const headings = document.querySelectorAll('#av_section_1 .av-special-heading-tag .av-heading-link');
            return Array.from(headings).map(link => link['text']);
        });
        const required_content_classes = await page.evaluate(() => {
            const section_actual_require_classes = {};
            document.querySelectorAll('#av_section_1 .av_textblock_section').forEach((item) => {
                const section_classes = item.className;
                const section_classes_array = section_classes.split(" ").filter(className => className !== "");
                const section_classes_array_last_value = section_classes_array[section_classes_array.length - 1];
                const section_class = section_classes.replace(/\s/g, '');
                section_actual_require_classes[section_class] = section_classes_array_last_value;
            });
            return section_actual_require_classes;
        });
        const descriptions = await page.evaluate((required_content_classes) => {
            let contentArray = [];
            let index = 0;
            for (const key in required_content_classes) {
                if (Object.prototype.hasOwnProperty.call(required_content_classes, key)) {
                    const required_class = required_content_classes[key];
                    const elements = document.querySelectorAll('#av_section_1 .' + required_class + ' .avia_textblock');
                    if (elements) {
                        contentArray[index] = contentArray[index] || [];
                        elements.forEach((ele) => {
                            contentArray[index] += ele.innerHTML;
                        });
                    }
                }
                index++;
            }
            return contentArray;
        }, required_content_classes);
        const slugs = headings.map(item => this.to_slug(item));
        console.log('headings', headings);
        console.log('slugs', slugs);
        console.log('descriptions', descriptions);
        console.log('images', images);
        const existingEvents = await this.eventModel.findAll({
            where: {
                slug: {
                    [sequelize_2.Op.in]: slugs,
                },
            },
        });
        const existingSlugs = existingEvents.map(event => event.slug);
        const missingIndexes = slugs
            .map((slug, index) => (!existingSlugs.includes(slug) ? index : null))
            .filter(index => index !== null);
        const missingEvents = missingIndexes.map(index => ({
            event_name: headings[index],
            slug: slugs[index],
            description: descriptions[index],
            image_url: images[index],
            status: 1,
            image_status: 1
        }));
        await this.eventModel.bulkCreate(missingEvents);
        await browser.close();
        this.logger.debug('---Cron End---');
    }
};
exports.TaskService = TaskService;
__decorate([
    (0, schedule_1.Cron)('* * * * *'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], TaskService.prototype, "handleCron", null);
exports.TaskService = TaskService = TaskService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, sequelize_1.InjectModel)(event_entity_1.Event)),
    __metadata("design:paramtypes", [Object])
], TaskService);
//# sourceMappingURL=task.service.js.map