const log = require('electron-log');
const path = require('path');
const fs = require('fs');
const childProcess = require('child_process');

const getAppropriateSizeFromBytes = require('../utils/getAppropriateSizeFromBytes.js');
const createDirectories = require('../utils/fs/createDirectories.js');

const RamDisk = class RamDisk {
    constructor(options = {}) {
        this.path = (process.platform === 'win32' ? 'R:\\' : '/ram');
        this.isExists = false;
        this.map = new Map();

        this.init();
    }

    init() {
        return;

        this.isExists = fs.existsSync(this.path);

        if (!this.isExists) {
            return;

            if (process.platform === 'linux') {
                childProcess.execSync(`sudo mkdir ${this.path}`);

                this.isExists = fs.existsSync(this.path);

                if (this.isExists) {
                    // childProcess.execSync('sudo ')
                    /*fs.appendFileSync('/etc/fstab')
                    const file = fs.createWriteStream(, { flags: 'a' });

                    file.write(`tmpfs   ${this.path}   tmpfs   defaults,noatime,mode=1777,size=1024M   0   0`);
                    file.end();*/


                    childProcess.execSync(`sudo chmod -R 777 ${this.path}`);
                    childProcess.execSync('sudo mount -a');
                }
            }

            return log.error(`[RamDisk] not exists in "${this.path}"`);
        }

        log.info(`[RamDisk] is exists in "${this.path}" size "${this.freeSpaceStr}"`);
    }

    save(filePath) {// check free space, write, check hash
        if (!this.isExists) {
            return filePath;
        }

        if (this.map.has(filePath)) {
            return this.map.get(filePath);
        }

        const parsed = path.parse(filePath);
        const newPath = path.join(this.path, parsed.dir.substring(parsed.root.length), parsed.base);

        createDirectories(newPath);

        fs.copyFileSync(filePath, newPath);

        // if (md5File.sync(newPath) !== hash) {
        //     return null;
        // }

        this.map.set(filePath, newPath);

        log.info(`[RamDisk] save to "${newPath}"`);

        return newPath;
    }

    remove() {

    }

    get freeSpace() {
        return fs.statSync(this.path).size;
    }

    get freeSpaceStr() {
        return getAppropriateSizeFromBytes(this.freeSpace);
    }
};

module.exports = RamDisk;
