import { IAggregator, INewsItem } from "./aggregator";
import { getRepository } from "typeorm";
import { AggroNewsItem } from "@shared/db/entity/AggroNewsItem";
import cheerio from "cheerio";
import { logger } from "src/logging";
import got from "got";

const updatePage = "http://com3d2.jp/update/";
const changeLogPattern = /\[\s*([^\s\]]+)\s*\]\s*((・.*)\s+)+/gim;
const FEED_NAME = "com3d2-jp-updates";

function getVersionNumber(verStr: string) {
    let verPart = verStr.replace(/[.\s]/g, "");
    if(verPart.length < 4)
        verPart += "0";
    return +verPart;
}

async function aggregate() {
    const repo = getRepository(AggroNewsItem);
    
    let lastPost = await repo.findOne({
        select: [ "newsId" ],
        where: { feedName: FEED_NAME },
        order: { newsId: "DESC" }
    });

    if(!lastPost)
        lastPost = repo.create({
            newsId: 0
        });
    
    try {
        const mainPageRes = await got.get(updatePage);

        if(mainPageRes.statusCode != 200) {
            logger.error("[COM3D2 JP UPDATE] Failed to load page. Got response code: %s", mainPageRes.statusCode);
            return [];
        }
        
        const rootNode = cheerio.load(mainPageRes.body);

        const readme = rootNode("div.readme");

        if(!readme) {
            logger.error("[COM3D2 JP UPDATE] Failed to find listing!");
            return [];
        }

        const latestVersionChangelog = changeLogPattern.exec(readme.text());

        if(!latestVersionChangelog)
            return [];

        const version = getVersionNumber(latestVersionChangelog[1]);
        const text = latestVersionChangelog[0];

        if(version <= lastPost.newsId)
            return [];
        
        return [{
            feedId: FEED_NAME,
            newsId: version,
            link: updatePage,
            title: latestVersionChangelog[1],
            author: "COM3D2 UPDATE",
            contents: text,
            embedColor: 0xcccccc,
            needsTranslation: true
        }] as INewsItem[];
    } catch(err) {
        logger.error("Failed to parse com3d2 update site: %s", err);
        return [];
    }
}

export default {
    aggregate: aggregate
} as IAggregator;