import fs from 'fs';
import {
    EncryptionAlgorithm,
    MatrixClient,
    MessageEvent,
    RustSdkCryptoStorageProvider,
    SimpleFsStorageProvider,
} from "matrix-bot-sdk";

const configPath = './config.json';

const logError = (message) => {
    let time = new Date;
    console.error(`[${time.toLocaleString()}] [LOG] [E] ${message}`);
};

const logInfo = (message) => {
    let time = new Date;
    console.log(`[${time.toLocaleString()}] [LOG] [I] ${message}`);
};

const readConfig = () => {

    if (!fs.existsSync(configPath)) {

        fs.writeFileSync(configPath,
            `{
                "homeserverURL": "https://matrix.org/",
                "token": "Super secret token! Do not show to anyone! Even your mum! ;)",
                "maxAmountOfPhotoesPerUser": 5
            }`
        );

        logError('[LOG] [E] Config file was not found. I have created a template, please, edit it and restart a bot.');

        process.exit(-1);
    }

    return JSON.parse(fs.readFileSync(configPath));
};

const uploadMediaFromEvent = async (client, event) => {
    const message = new MessageEvent(event);
    const fileEvent = new MessageEvent(message.raw);
    const decrypted = await client.crypto.decryptMedia(fileEvent.content.file);
    const mxc = await client.uploadContent(decrypted);
    return mxc;
};

const convertMsgType = (msgtype) => {
    switch (msgtype) {
        case "m.image":
            return "p";
        case "m.video":
            return "v";
        case "m.text":
            return "t";
        default:
            return msgtype;
    }
};

export { readConfig, logError, logInfo, uploadMediaFromEvent, convertMsgType };