/**
* Created by Gifer on 30.08.2016.
*/

"use strict";

const fs      = require('fs');
// const Service = require('./service');
const os      = require('os');
const console = require('gifer-console');

const MCPROFILE = "mcprofile.dat";

let rootPath    = ""; // path to mychat profile folder
let rootProfile = "";
let profileZIP  = null;
let zipEntries  = [];
let __profile   = {};

function makeProfile(profilePath) {
    try {
        profileZIP.extractAllTo(profilePath, true);
    } catch (e){
        console.immediately(e.message || e);
    }
}

__profile.init = function (appPath) {
    rootPath = appPath || "/";

    if (rootPath[rootPath.length - 1] !== "/") {
        rootPath += "/";
    }

    try {
        profileZIP = new require('adm-zip')(rootPath + MCPROFILE);

        zipEntries = profileZIP.getEntries();
    } catch (e) {
        console.err(e.message || e);
    }
};

__profile.getProfilePath = function (){
    let path     = process.argv[0].replace(/\\/g, "/");
    let pathArr  = path.split('/');
    let dataRoot = ''; // path to mcprofile.dat
    let subDir   = '';

    switch (os.platform()){
        case "darwin":
            dataRoot = process.env.HOME;

            let item = pathArr.shift();

            while (item.indexOf('.app') === -1){
                item = pathArr.shift();
            }

            subDir   = item.replace('.app', '');
        break;

        case "linux" :
            dataRoot = process.env.HOME;
            subDir   = pathArr[pathArr.length - 2];
        break;

        case "win32" :
            dataRoot = process.env.LOCALAPPDATA;
            subDir   = pathArr[pathArr.length - 2];
        break;
    }

    rootProfile = (dataRoot + "/" + subDir).replace(/\\/g, "/");

    return rootProfile;
};

__profile.testProfile = function () {
    let path        = __profile.getProfilePath();
    let dbPath      = null;
    let profileFile = null;

    try {
        dbPath = fs.statSync(path + "/db/main.db");
    } catch(e){
        //console.err("Not found: "  + path);
    }

    try {
        profileFile = fs.statSync(rootPath + MCPROFILE);
    } catch(e){
        console.err("Not found: " + rootPath + MCPROFILE);

        setTimeout(function () {
            process.exit(900);
        }, 60);
    }

    if (profileFile && !dbPath){
        makeProfile(path.replace(/\\/g, "/"));
    }
};

__profile.extractFile = function (filePathInProfile) {
    if (!rootProfile) {
        __profile.getProfilePath();
    }

    try {
        profileZIP.extractEntryTo(filePathInProfile, rootProfile, true, true);
    } catch (e){
        console.immediately(e.message || e);
    }
};

module.exports = __profile; //Service.MargeObj(module.exports, __profile);


