const {app, remote} = require('electron');
const fs = require('fs');
const path = require('path');
const log = require('electron-log');
const md5File = require('md5-file');

const heshFile = path.join(app.getPath('userData'), 'hesh-checked.json');

const check = (itemPath, itemHesh) => {
    try {
        const itemFullPath = path.join(app.getPath('userData'), itemPath);
        let checked = false;

        if ( fs.existsSync(itemFullPath) && md5File.sync(itemFullPath) === itemHesh ) {
            log.info('item checked '+ itemPath +' succesfully');

            checked = true;
        } else {
            log.warn('check item hesh '+ itemPath +' has broken');

            checked = false;
        }

        return checked;
    } catch (e) {
        log.error('mod:heshChecker.check-item()', e);
    }
};

const find = (itemPath, itemHesh) => {
    try {
        let heshes = {};

        if ( fs.existsSync(heshFile) ) {
            heshes = JSON.parse(fs.readFileSync(heshFile));
        }

        return (heshes[itemPath] && heshes[itemPath] === itemHesh);
    } catch (err) {
        log.error('mod:heshChecker.find()', err);
    }
};

const save = (itemPath, itemHesh) => {
    try {
        let heshes = {};

        if ( fs.existsSync(heshFile) ) {
            heshes = JSON.parse(fs.readFileSync(heshFile));
        }

        heshes[itemPath] = itemHesh;

        fs.writeFileSync(heshFile, JSON.stringify(heshes));
    } catch (err) {
        log.error('mod:heshChecker.save()', err);
    }
};

const remove = (itemPathOrHesh) => {
    try {
        let heshes = {};

        if ( fs.existsSync(heshFile) ) {
            heshes = JSON.parse(fs.readFileSync(heshFile));
        }

        if ( heshes[itemPathOrHesh] ) {
            delete heshes[itemPathOrHesh];
        } else {
            for ( let key in heshes ) {
                if ( heshes[key] === itemPathOrHesh ) {
                    delete heshes[key];

                    break;
                }
            }
        }

        fs.writeFileSync(heshFile, JSON.stringify(heshes));
    } catch (err) {
        log.error('mod:heshChecker.remove()', err);
    }
};

const clearFile = () => {
    try {
        fs.writeFileSync(heshFile, JSON.stringify({}));
    } catch (err) {
        log.error('mod:heshChecker.clearFile()', err);
    }
};

module.exports = {
    check: check,
    find: find,
    save: save,
    remove: remove,
    clearFile: clearFile
};
