

/* 文件大小格式化 */
export function formatFileSize(size) {
  const Unit = ["Bytes", "Kb", "Mb", "Gb", "Tb"];
  //const Unit = ["byte", "K", "M", "G", "T"];
  let s, i;
  for(s = size, i = 0; s >= 1024 && i < Unit.length - 1; s /= 1024, i++);
  return s.toFixed(2).replace(/\.00$/, '') + Unit[i];
}

export function save(name, src) {
  let a = 0;
  let url = null;
  try
  {
    url = window.URL.createObjectURL(new Blob([src]))
    a = document.createElement('a');
    document.body.append(a);
    a.style.display = 'none'
    a.href = url;
    a.setAttribute('download', name)
    a.click();
    return true;
  }
  catch(e)
  {
    console.error(e);
    return false;
  }
  finally
  {
    if(a)
      a.remove();
    if(url)
      window.URL.revokeObjectURL(url);
  }
}

export function image_size(file) {
  return new Promise((resolve, reject) => {
    try
    {
      let url = URL.createObjectURL(file);
      let img = new Image();
      img.src = url;
      if(img.complete)
      {
        //console.log('complete', img.width, img.height);
        resolve({
          width: img.width,
          height: img.height,
        });
      }
      else
      {
        img.onload = () => {
          //console.log('async', img.width, img.height);
          resolve({
            width: img.width,
            height: img.height,
          });
        };
      }
    }
    catch(e)
    {
      reject(e);
    }
  });
}
