import * as piexif from "piexifjs";

// 读取图片的EXIF信息
export function readExif(file: Blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const exif = piexif.load(e.target.result);
      console.log(exif);
      resolve(exif);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

function convertToDMS(value: number) {
  const degrees = Math.floor(value);
  const minutes = Math.floor((value - degrees) * 60);
  const seconds = (value - degrees - minutes / 60) * 3600;
  return [degrees, minutes, seconds];
}

function createGPSIFD(lat: number, lon: number, alt: number) {
  const latDMS = convertToDMS(Math.abs(lat));
  const lonDMS = convertToDMS(Math.abs(lon));

  const gpsIFD = {
    [piexif.GPSIFD.GPSVersionID]: [2, 3, 0, 0],
    [piexif.GPSIFD.GPSLatitudeRef]: lat >= 0 ? "N" : "S",
    [piexif.GPSIFD.GPSLatitude]: [
      [latDMS[0], 1],
      [latDMS[1], 1],
      [latDMS[2] * 100, 100],
    ],
    [piexif.GPSIFD.GPSLongitudeRef]: lon >= 0 ? "E" : "W",
    [piexif.GPSIFD.GPSLongitude]: [
      [lonDMS[0], 1],
      [lonDMS[1], 1],
      [lonDMS[2] * 100, 100],
    ],
    [piexif.GPSIFD.GPSAltitudeRef]: alt >= 0 ? 0 : 1,
    [piexif.GPSIFD.GPSAltitude]: [Math.abs(alt), 1],
  };
  return gpsIFD;
}

// 图片中加入经纬度exif信息， 必须是jpg格式的文件流
export const attachImageCoord = (blob: Blob, latlngalt: number[]) => {
  const reader = new FileReader();

  const promise = new Promise<Blob>((resolve) => {
    reader.onload = function (event) {
      const exifObj = piexif.load(event.target.result);
      const gpsIFD = createGPSIFD(latlngalt[0], latlngalt[1], latlngalt[2]);
      exifObj["GPS"] = gpsIFD;

      const exifBytes = piexif.dump(exifObj);
      const newImageData = piexif.insert(exifBytes, event.target.result);

      const base64Data = newImageData.split(",")[1];
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: "image/jpeg" });
      resolve(blob);
    };
  });
  reader.readAsDataURL(blob);

  return promise;
};
