let fs = require('fs');
let request = require('request');
let path = require("path");

let System = function () {
    let version = "3.0";

    let AUDIO_EXTENSION = ".ogg";
    let IMAGE_EXTENSION = ".jpg";

    let isDir = function(path) {
        try {
            return fs.statSync(path).isDirectory();
        }
        catch (e) {
            return false;
        }
    }

    let isFile = function(path) {
        try {
            return fs.statSync(path).isFile();
        }
        catch (e) {
            return false;
        }
    }

    let makeDir = function (path) {
        if (!isDir(path)) {
            fs.mkdirSync(path);
        }
    }

    let download = function(uri, path, callback) { console.log("download:" + path);
        request.head(uri, function(err, res, body){
            request(uri).pipe(fs.createWriteStream(path)).on('close', callback);
        });
    }

    let getAppDir = function () {
        return path.dirname(process.execPath);
    }

    let getDbFolder = function () {
        return getDataFolder() + "/db"
    }

    let getDataFolder = function () {
        return getAppDir() + "/data"
    }

    let getPicFolder = function () {
        return getDataFolder() + "/pic"
    }

    let getAudioFolder = function () {
        return getDataFolder() + "/audio"
    }

    let getImagesFolder = function () {
        return getDataFolder() + "/image"
    }

    let downloadImage = function(url, name) {
        let filePath = getImagesFolder() + "/" + name + IMAGE_EXTENSION;
        download(url, filePath);
    }

    let downloadAudio = function(url, name) {
        let filePath = getAudioFolder() + "/" + name + AUDIO_EXTENSION;
        download(url, filePath);
    }

    let downloadPic = function(url, name) {
        let filePath = getPicFolder() + "/" + name + IMAGE_EXTENSION;
        download(url, filePath);
    }

    return {
        audioExtension: function () {
            return AUDIO_EXTENSION;
        },
        imageExtension: function () {
            return IMAGE_EXTENSION;
        },

        getVersion: function () {
            return version;
        },

        isDir: isDir,
        isFile: isFile,
        getAppDir: getAppDir,
        getDbFolder: getDbFolder,
        getPicFolder: getPicFolder,
        getImagesFolder: getImagesFolder,
        getAudioFolder: getAudioFolder,
        downloadImage: downloadImage,

        downloadAudio: function(url, name) {
            download(url, name, function() {
                console.log('done');
            });
        }
    }
}();

module.exports = System;