function then(onthen) {
  this._then_callback = function (p) { };
  this._error_callback = function (p) { };
  this._on_then = onthen;
}

function JsFormData() {
  this.boundry = "";
  this.formName = "";
  this.formValue = "";
}
JsFormData.prototype.constructor = JsFormData;
JsFormData.prototype.getFormString = function () {
  return "--" + this.boundry + "\r\nContent-Disposition:form-data; name=" + this.formName + "\r\n\r\n" + this.formValue + "\r\n";
};
JsFormData.prototype.toString = function () {
  return this.getFormString();
};

function JsFileFormData() {
  this.formFileName = "";
  this.contentType = "";
  JsFormData.call(this);
}
JsFileFormData.prototype = new JsFileFormData();
JsFileFormData.prototype.constructor = JsFileFormData;
JsFileFormData.prototype.getFormString = function () {
  return "--" + this.boundry + "\r\nContent-Disposition:form-data; name=" + this.formName + "; filename=" + this.formFileName + "\r\nContent-Type: " + this.contentType + "\r\n\r\n" + this.formValue + "\r\n";
};
JsFileFormData.prototype.toString = function () {
  return this.getFormString();
};
then.prototype.constructor = then;
then.prototype = new then();
then.prototype.then = function (p) {
  this._then_callback = p;
  this._on_then();
  return this;
};
then.prototype.error = function (p) {
  this._error_callback = p;
  return this;
}
then.prototype.invoke_then = function (p) {
  this._then_callback(p);
  return this;
}
then.prototype.invoke_error = function (p) {
  this._error_callback(p);
  return this;
}

function JsHttpHelper() {
  this.formData = new Array();
}
JsHttpHelper.prototype.boundry = Math.random().toString().substr(2),
  JsHttpHelper.prototype.addFormValue = function (key, value) {
    var f = new JsFormData();
    f.formName = key;
    f.formValue = value;
    f.boundry = this.boundry;
    this.formData.push(f);
  };
JsHttpHelper.prototype.addFileFormValue = function (key, fname, fcontent) {
  var f = new JsFileFormData();
  f.formName = key;
  f.formValue = fcontent;
  f.contentType = "application/octet-stream";
  f.formFileName = fname;
  f.boundry = this.boundry;
  this.formData.push(f);
};
JsHttpHelper.prototype.postMultipartFormData = function (url, postCallBack, updateProgress, errorFunc) {
  var xhr = new XMLHttpRequest();
  // xhr.onloadend = function (e) {
  //   if (e.total > 0)
  //     postCallBack(e, xhr);
  // };
  xhr.onload = function (e) {
    if((e.status >= 200 && e.status < 300) || e.status == 304){
      postCallBack(e, xhr);
    }   
  };
  xhr.onabort = errorFunc;
  xhr.onerror = errorFunc;
  xhr.ontimeout = errorFunc;
  if (updateProgress != null) {
    xhr.upload.onprogress = function (e) {
      if (e.lengthComputable) {
        updateProgress((e.loaded / e.total) * 100);
      }
    }
  };
  xhr.open("POST", url, true);
  xhr.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + this.boundry);
  var postBody = "";
  // console.log(this.formData);
  for (var s = 0; s < this.formData.length; s++) {
    postBody += this.formData[s].getFormString();
  }
  postBody += "--" + this.boundry + "--\r\n";
  xhr.send(postBody);
  this.formData = new Array();
  console.log(this.formData);
};

JsHttpHelper.prototype.constructor = JsHttpHelper;

var lastFileInput;

function compress_image(base64Image, callback, wd) {
  if (wd == null || wd == undefined) {
    wd = 200;
  }
  var image = document.createElement("img");
  image.onload = function () {
    var square = wd;
    var canvas = document.createElement('canvas');
    var HoverW = this.height / this.width;
    var hNew = wd * HoverW;
    var wNew = wd;
    canvas.width = wNew;
    canvas.height = hNew;
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(this, 0, 0, this.width, this.height, 0, 0, wNew, hNew);
    var data = canvas.toDataURL('image/jpeg');
    //console.log("compress_image raw " + base64Image.length + " now " + data.length + " decrease rate " + (base64Image.length - data.length) / base64Image.length);
    callback(data);
  };
  image.setAttribute('src', base64Image);
}

function read_file_base64String(funcReadOver, funcReadOutoffLimit, sizeLimit) {
  if (sizeLimit == null || sizeLimit == undefined) {
    sizeLimit = 200;
  }
  lastFileInput = document.getElementById("f1_id");
  if (lastFileInput != null) {
    document.body.removeChild(lastFileInput);
    lastFileInput = null;
  }
  if (lastFileInput == null) {
    lastFileInput = document.createElement("input");
    lastFileInput.type = "file";
    lastFileInput.name = "f1";
    lastFileInput.id = "f1_id";
    lastFileInput.setAttribute("style", "display:none;");
    document.body.appendChild(lastFileInput);
  }
  lastFileInput.onchange = null;
  lastFileInput.onchange = function (e) {
    var f = lastFileInput.files[0];
    var reader = new FileReader();
    var sz = ((f.size / 1024) / 1024);
    //console.log(sz + "m");
    reader.onloadend = function (e) {
      compress_image(e.target.result, function (bs64) {
        funcReadOver(bs64);
      }, sizeLimit);
      //1M == 1398211 
    };
    reader.readAsDataURL(f);
  };
  lastFileInput.click();
}

function upload(url,func, keyValues, isfile, accept) {
  // var proc = progressBar.start();
  lastFileInput = document.getElementById("f1_id");
  if (lastFileInput != null) {
    document.body.removeChild(lastFileInput);
    lastFileInput = null;
  }
  if (lastFileInput == null) {
    lastFileInput = document.createElement("input");
    lastFileInput.type = "file";
    lastFileInput.name = "f1";
    lastFileInput.id = "f1_id";
    accept && (lastFileInput.accept = accept);
    lastFileInput.setAttribute("style", "display:none;");
    document.body.appendChild(lastFileInput);
  }
  lastFileInput.onchange = null;
  lastFileInput.onchange = function (e) {  
    var f = lastFileInput.files[0];
    var reader = new FileReader();
    reader.onloadend = function (e) {
      var sz = ((f.size / 1024) / 1024);
      if (isfile != undefined && isfile!=='') {
        var http = new JsHttpHelper();
        http.addFileFormValue("f2", f.name, e.target.result);
        if(keyValues){
          for (var key in keyValues) {
            http.addFormValue(keyValues[key].key, keyValues[key].value);
          }
        }
        http.postMultipartFormData(url, func, null, function (e, xhr) {         
        });
      } else {       
        compress_image(e.target.result, function (bs64) {        
          var http = new JsHttpHelper();
          http.addFileFormValue("f2", f.name, bs64);
          if(keyValues){
            for (var key in keyValues) {
              http.addFormValue(keyValues[key].key, keyValues[key].value);
            }
          }
          http.postMultipartFormData(url, func, null, function (e, xhr) {           
          });
        });
      }
      //1M == 1398211
    };
    reader.readAsDataURL(f);
  };
  lastFileInput.click();
}

export default{
  compress_image,
  read_file_base64String,
  upload
}