/**
 * Created with JetBrains WebStorm.
 * User: Cmma
 * Date: 7/23/14
 * Time: 10:33 AM
 * To change this template use File | Settings | File Templates.
 */

define(function (require, exports) {

    var userSvc = require('../../../../share/assert/js/usersvc').userSvc;
    var request = window.require('request');
    var fs = window.require('fs');


    function formateParams(obj) {
        var params = "";
        for(var p in obj) {
            params += p + "=" + obj[p] + "&";
        }
        return encodeURI(params.substr(0, params.length - 1));
    }

    var fileID = "";
    var saveFileName = "";

    function deleteFileByID(fileID, callback) {
        var paramObj = {
            "method" : "pan.file.delete",
            "version" : "1.0",
            "format" : "json",
            "uid" :  userSvc.uuid,
            "fileid" : fileID
        }
        var params = formateParams(paramObj);

        $.post(AppRemoteSvcCfg.ResSvcUrl + "?" + params, null, function(data) {
            if(data != "") {
                callback();
            }
        })
    }

    function setFileID(value) {
        fileID = value;
    }

    function getFilesizeInBytes(filename) {
        var stats = fs.statSync(filename);
        var fileSizeInBytes = stats["size"];
        return fileSizeInBytes;
    }

    function uploadPackage(icwProgressCallback, icwFinishCallback) {

        var fileName = Global.saveToPath.substr(Global.saveToPath.lastIndexOf("\\") + 1);
        fileName = fileName.substr(0, fileName.lastIndexOf("."));
        userSvc.getToken(function(token) {
            if(!token) {
                icwFinishCallback("123", 401, "");
                return;
            }
            var paramObj = {
                "method" : "pan.file.add",
                "version" : "1.0",
                "format" : "json",
                "uid": userSvc.uuid,
                "fileName" : fileName,
                "folderType" : "yun_wendang",
                "access_token": token,
                "appkey": "Hb0YhmOo"
            };

            var params = formateParams(paramObj);
            var fileSize = getFilesizeInBytes(Global.saveToPath);
//            console.log("fileSize: " + fileSize);
            var formData = {
                filename: fileName,
                filesize: fileSize,
                multiFile: fs.createReadStream(Global.saveToPath)
            };
            var req = request.post({url:AppRemoteSvcCfg.ResSvcUrl+"?"+params.toString(), formData: formData}, function optionalCallback(err, httpResponse, body) {
                if (err) {
                    console.error('upload failed:', err);
                }
//                console.log(httpResponse);
                icwFinishCallback("123",httpResponse.statusCode,body);
            });

             var requestSize = 0,bytesDispatched = 0,progress=0;
            setTimeout(function(){
                var _callee = arguments.callee;
                requestSize = req.headers['content-length'];
//                console.log("requestSize: " + requestSize);
                if(requestSize){
                    bytesDispatched =  req.req.connection._bytesDispatched;
//                    console.log("bytesDispatched: " + bytesDispatched);
                    progress = (bytesDispatched/requestSize) * 100;
                    if(bytesDispatched >= requestSize)
                    {
                        progress = 100;
                        icwProgressCallback("123",progress);
                    }
                    else{
                        icwProgressCallback("123",progress);
                        setTimeout(_callee,200);
                    }
                }
            },200);
        });
    }

    exports.uploadPackage = uploadPackage;
    exports.setFileID = setFileID;
})