var http = require("http");
var fs = require("fs");
var path = require("path");

/**
 * 下载回调
 */
function getHttpReqCallback (imgSrc, filePath, fileName,
     downloadProgress, 
     downloadEnd, downloadError) {

    var dirName =  path.join(__dirname, filePath);
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath);
        console.log("文件夹创建成功");
    } else {
        console.log("文件夹已存在");
    }
    
    var callback = function(res) {
        console.log("request: " + imgSrc + " return status: " + res.statusCode);
        var contentLength = parseInt(res.headers['content-length']);
        
        var downLength = 0;
    
        var out = fs.createWriteStream(dirName + "/" + fileName);
        res.on('data', function (chunk) {
            
            downLength += chunk.length;
            var progress =  Math.floor(downLength*100 / contentLength);
            downloadProgress(progress + "%")
            //写文件
            out.write(chunk, function () {
                //console.log(chunk.length);
                
            });
            
        });
        res.on('end', function() {
            downFlag = false;
            console.log("end downloading " + imgSrc);
            downloadEnd("DownLoad Success")
            if (isNaN(contentLength)) {
                console.log(imgSrc + " content length error");
                downloadError(imgSrc + " content length error")
                return;
            }
            if (downLength < contentLength) {
                console.log(imgSrc + " download error, try again");
                downloadError(imgSrc + " download error, try again");
                return;
            }
        });
    };

    return callback;
}

/**
 * 下载开始
 */

var ktdownload = {
    /**
     * 快速下载方法
     * @param {string} downSrc 下载地址
     * @param {string} dirName 文件夹目录
     * @param {string} fileName 文件名
     * @param {any} progress 进度回调
     * @param {any} end 结束下载
     * @param {any} failed 失败回调
     */
    startDownloadTask (downSrc, dirName,fileName, progress, end, failed) {
        console.log("start downloading " + downSrc);
        var req = http.request(downSrc, getHttpReqCallback(downSrc, dirName, fileName, (res)=>{
            progress(res)
        },
        (downloadEnd)=>{
            end(downloadEnd)
        },
        (downloadError)=>{
            failed(downloadError)
        }
        ));
        req.on('error', function(e){
            console.log("request " + downSrc + " error, try again");
            failed(e)
        });
        req.end();
    }
}

module.exports = ktdownload