
const fs = require('fs');

function fileExists(filePath){
    const rMode = fs.constants ? fs.constants.R_OK : fs.R_OK;
    const wMode = fs.constants ? fs.constants.W_OK : fs.W_OK;
    return new Promise((resolve) => {
        fs.access(filePath, rMode | wMode, (err) => { //eslint-disable-line no-bitwise
            if(err){
                resolve(false);
            }else{
                resolve(true);
            }
        });
    });
}

function writeFile(filePath, data) {
    return new Promise((resolve, reject) => {
        fs.writeFile(filePath, data, function(err) {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function copyFile(src, dest) {
    return new Promise((resolve, reject) => {
        fs.copyFile(src, dest, (err) => {
            if(err){
                reject(err);
            }else{
                resolve();
            }
        });
    });
}

function readFile(src) {
    return new Promise((resolve, reject) => {
        fs.readFile(src, function(err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

// For the options param, see: https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_mkdir_path_options_callback
function mkdir(dir, options) {
    return new Promise((resolve, reject) => {
        fs.mkdir(dir, options, (err) => {
            if(err){
                reject(err);
            }else{
                resolve();
            }
        });
    });
}

function removeFile(filePath, data) {
    return new Promise((resolve, reject) => {
        fs.unlink(filePath, function(err) {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

module.exports = {
    // simplified function for checking if a file exists and is accessible
    fileExists,
    writeFile,
    copyFile,
    readFile,
    mkdir,
    removeFile
};
