import { Message } from "discord.js";
import got from "got";
import { logger } from "src/logging";
import { Command, ICommandData, Plugin } from "src/model/plugin";
import { tryDo } from "src/util";

const rcgRe = /<input id="rcg_image".+value="([^"]+)".*\/>/i;

interface XkcdResponse {
    img: string;
}

@Plugin
export class Rcg {
    async sendErrorMessage(msg: Message): Promise<void> {
        const xkcdResult = await tryDo(got.get<XkcdResponse>("https://xkcd.com/info.0.json", { responseType: "json" }));
        if(!xkcdResult.ok || !xkcdResult.result) {
            await msg.reply("sorry, I couldn't get any comics :(.");
            return;
        }
        await msg.reply("sorry, I couldn't get a random comic! Here is today's XKCD instead:", {
            files: [ xkcdResult.result.body.img ]
        });
    }

    @Command({
        type: "mention",
        pattern: "random comic",
        auth: false,
        documentation: {description: "Generates a comic just for you!", example: "random comic"}
    })
    async randomComic({ message }: ICommandData): Promise<void> {
        const result = await tryDo(got.get("http://explosm.net/rcg/view/?promo=false"));
    
        if (!result.ok) {
            logger.error("Failed to get RCG. Got error: %s", result.error);
            await this.sendErrorMessage(message);
            return;
        }

        const regexResult = rcgRe.exec(result.result.body);

        if(!regexResult) {
            logger.error("Could not find RCG from body. Got response body: %s", result.result.body);
            await this.sendErrorMessage(message);
            return;
        }

        const messagePostResult = await tryDo(message.reply("I find this very funny:", {
            files: [ regexResult[1].trim() ]
        }));

        if (!messagePostResult.ok) {
            logger.error("Failed to get RCG. Got error: %s", messagePostResult.error);
            await this.sendErrorMessage(message);
        }
    }
}