const config = require('./config.json');
const discordToken = config.token;
const outputFile = config.path;
const Discord = require('discord.js');
const fs = require('fs');
const readline = require('readline');

const client = new Discord.Client({
    intents: [
        Discord.GatewayIntentBits.Guilds,
        Discord.GatewayIntentBits.MessageContent,
        Discord.GatewayIntentBits.GuildMessages
    ]
})

async function parseMessages() {
    try {
        const fileStream = fs.createReadStream('message.txt');

        const rl = readline.createInterface({
            input: fileStream,
            crlfDelay: Infinity
        });

        let lines = [];
        for await (const line of rl) {
            // Process the line.
            let newline = "*"+line.replace(/ -/g, " - ").replace(/- /g, " - ").replace(/  /g, " ").replace(/- /g, '* - **').replace(/"/g, "'").replace(/ \* - \*\*/g, "*\n - **")+"**";
            /*
            let newline1 = line.replace(/-/g, " - ");
            let newline2 = newline1.replace(/  /g, " ");S
            let newLine3 = '*' + newline2.replace(/- /g, '* - **') + '**';
            let newline4 = newLine3.replace(/"/g, "'");
            */
            console.log("Writing: " + newline)
            lines.push(newline);
        }

        // Write to JSON file
        fs.writeFileSync(outputFile, JSON.stringify(lines, null, 2));
    } catch (error) {
        console.error('An error occurred:', error);
    }
};

async function fetchAllMessages() {
    return new Promise(async (resolve, reject) => {
        const channel = client.channels.cache.get("1184068486436229160");
        let messages = [];

        // Create message pointer
        let message = await channel.messages
            .fetch({
                limit: 1
            })
            .then(messagePage => (messagePage.size === 1 ? messagePage.at(0) : null));

        while (message) {
            await channel.messages
                .fetch({
                    limit: 100,
                    before: message.id
                })
                .then(messagePage => {
                    messagePage.forEach(msg => messages.push(msg));

                    // Update our message pointer to be the last message on the page of messages
                    message = 0 < messagePage.size ? messagePage.at(messagePage.size - 1) : null;
                });
        }

        messages.forEach(msg => {
            const regex = /\- ?\S+$/;
            const text = msg.content.replace(/\r?\n/g, ' ');

            if (regex.test(text)) {
                fs.appendFile('message.txt', text + "\n", function(err) {
                    if (err) reject(err);
                });
            }
        });

        resolve();
    });
}

client.on('ready', async () => {
    console.log("Ready!")

    fs.writeFile('message.txt', '', function(err) {
        if (err) {
            return console.log(err);
        }
        console.log("File was cleared!");
    });

    fetchAllMessages().then(() => {
        parseMessages();
    }).catch((err) => {
        console.error('An error occurred:', err);
    });
});


client.on('messageCreate', message => {

    const regex = /\- ?\S+$/;
    const text = message.content;


    if (regex.test(text)) {

        fs.appendFile('message.txt', message.content.replace(/\r?\n/g, ' ') + "\n", function(err) {
            if (err) throw err;
        });

        parseMessages();
    }


});

client.login(discordToken);