function downloadNormal(url, fileName, isView) {
  return new Promise((next) => {
    var tag = document.createElement('a');
    tag.href = url;
    if(isView){
      tag.target = '_blank';
    }
    tag.download = fileName;
    document.body.appendChild(tag);
    tag.click();
    document.body.removeChild(tag);

    next(true);
  });
}

function downloadForce(url, fileName) {
  return new Promise((next) => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function() {
      var urlCreator = window.URL || window.webkitURL;
      var imageUrl = urlCreator.createObjectURL(this.response);
      var tag = document.createElement('a');
      tag.href = imageUrl;
      if (fileName) {
        tag.download = fileName;
      } else {
        tag.download = getFileName(url);
      }
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);

      next(true);
    }
    xhr.onerror = function() {
      next(false);
    }
    xhr.send();
  });
}

function getType(file) {
  var filename = file;
  var index1 = filename.lastIndexOf('.');
  var index2 = filename.length;
  var type = filename.substring(index1, index2);
  return type;
}

function getFileName(url){
  if(url.indexOf('/') < 0){
    return url;
  }
  var fileName = url.substring(url.lastIndexOf('/') + 1);
  if(fileName.indexOf('-') < 0){
    return fileName;
  }
  return fileName.substring(0, fileName.lastIndexOf('-'));
}

export default function(url, fileName, vesselBankFlag) {
  return new Promise(async(next) => {
    var type = getType(url);
    var isView = type === '.txt' || type === '.pdf';

    if(vesselBankFlag === 'B'){
      if(isView){
        next(await downloadNormal(url, fileName, isView));
      }else{
        next(await downloadForce(url, fileName));
      }
    }else{
      next(await downloadNormal(url, fileName, isView));
    }
  });
}
