const fs = require('fs');
const path = require('path');
const errorLogHandler = async (request, reply) => {
    await saveErrorLog(request.body);
    reply.send({ success: true });
};

const saveErrorLog = (ed) => {
    let fileName = getFileName();
    let today = getTodayDateFormat()
    let fileCount = getFileCount(today) == 0 ? 1 : getFileCount(today);
    let filePath = path.join(__dirname, `/../logging/${fileName}`);
    fs.exists(fileName, function (exists) {
        if (exists && getFilesizeInBytes(`${filePath}_${fileCount}.log`) < 0.500000) {
            fs.appendFile(`${filePath}_${fileCount}.log`, ed, function (err) {
                if (err) return false;
                return true;
            })
        } else if (getFilesizeInBytes(`${filePath}_${fileCount}.log`) > 0.500000) {
            fileCount = fileCount + 1;
            error_file = fs.createWriteStream(`${filePath}_${fileCount}.log`, { flags: 'a' });
            error_file.write('\n-----\n' + JSON.stringify(ed, null, 2) + '\n-----\n');
            return true;
        } else {

            error_file = fs.createWriteStream(`${filePath}_${fileCount}.log`, { flags: 'a' });
            error_file.write('\n-----\n' + JSON.stringify(ed, null, 2) + '\n-----\n');
            return true;
        }
    });
}

const getFilesizeInBytes = (filename) => {
    try {
        const stats = fs.statSync(filename)
        const fileSizeInBytes = stats.size
        const fileSizeInMegabytes = fileSizeInBytes / 1000000.0
        return fileSizeInMegabytes
    } catch (error) {
        return 0
    }
}

const getFileName = () => {
    try {
        let today = getTodayDateFormat()
        makeFolder(today);
        return `${today}/errorLog`;
    } catch (error) {
    }
}

const getTodayDateFormat = () => {
    try {
        let today = new Date();
        let dd = today.getDate();
        let mm = today.getMonth() + 1;
        let yyyy = today.getFullYear();
        if (dd < 10) dd = '0' + dd
        if (mm < 10) mm = '0' + mm
        today = mm + '_' + dd + '_' + yyyy;
        return today;
    } catch (error) {
        return "test_1234";
    }
}



const getFileCount = (name) => {
    let dir = path.join(__dirname, `/../logging/${name}`);
    files = fs.readdirSync(dir);
    return files.length;
}

const makeFolder = (t) => {
    let dir = path.join(__dirname, `/../logging/${t}`);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
}
module.exports = errorLogHandler;