var path = require("path");
var fs = require("fs");
var os = require('os'),
    clui = require('clui');
var util = require("./src/util")
var config = require("./src/config");
var Progress = clui.Progress;
var thisProgressBar = new Progress(20);
var progress = require('request-progress');
var log = require('single-line-log').stdout;
var unzip = require("unzip");
var fs = require("fs");
var path = require("path");
var request = require("request");

var repoUrl = "https://codeload.github.com/longyangxi/Flax/zip/master";
var projPath = null;

function doCreate(projName) {
    projPath = process.cwd() + "/" + projName;
    if (fs.existsSync(projPath)) {
        throw "There has already a not empty folder: " + projPath;
    }
    fs.mkdirSync(projPath);

    projPath = projPath + "/www";
    fs.mkdirSync(projPath);

    var targetZip = process.cwd() + "/flax.zip";
    console.log("downloading flax: " + repoUrl);
    progress(request(repoUrl)).on("progress", function(p) {
        log(thisProgressBar.update(p.size.transferred, p.size.total), (p.size.transferred / 1024 / 1024).toFixed(2) + "mb/" + (p.size.total / 1024 / 1024).toFixed(2) + "mb");
    }).pipe(fs.createWriteStream(targetZip)).on('close', function() {
        unzipTemplate(targetZip);
    });
}

function unzipTemplate(targetZip) {
    console.log("\n unzip: " + targetZip);

    fs.createReadStream(targetZip)
        .pipe(unzip.Extract({ path: projPath }))
        .on("close", function() {
            fs.unlinkSync(targetZip);
            util.copyDir(projPath + "/Flax-master/template", projPath);
            util.copyDir(projPath + "/Flax-master/src/", projPath + "/src");
            util.deleteFolderRecursive(projPath + "/Flax-master");
        });
}

module.exports = doCreate;