const drivelist = require('drivelist');
const fileSize = require('filesize')
const { exec } = require("child_process");

async function getDrives() {
    const drives = await drivelist.list();
    drives.forEach(function (item) {
        item.size = fileSize(item.size)
        if (item.mountpoints.length > 0) {
            item.path = item.mountpoints[0].path
        } else {
            item.path = 'N/A'
        }

    })
    return drives
}

async function mount(path1, path2) {
    return new Promise(function (resolve, reject) {
        exec(`sudo mount ${path1} ${path2}`, (error, stdout, stderr) => {
            if (error) {
                if (error.message.includes('already mounted')) {
                    resolve(true)
                    return;
                } else {
                    resolve(false)
                    return;
                }
            } if (stderr) {
                resolve(false)
                return;
            }
            resolve(true)
        })
    })
}

async function unMount(path1) {
    return new Promise(function (resolve, reject) {
        exec(`sudo umount ${path1}`, (error, stdout, stderr) => {
            if (error) {
                resolve(false)
                return;
            } if (stderr) {
                resolve(false)
                return;
            }
            resolve(true)
        })
    })
}

module.exports = {
    getDrives,
    mount,
    unMount
}