/**
 * KRA - Image Utility
 * Image compression and URL handling
 */

export default class ImageCompress {
  file: File;
  fileSize: number;
  maxWH: number;

  constructor(file: File, fileSize: number, maxWH = 1920) {
    this.file = file;
    this.fileSize = fileSize;
    this.maxWH = maxWH;
  }

  compress(): Promise<File> {
    const fileType = this.file.type;
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(this.file);
      reader.onload = () => {
        const canvas = document.createElement('canvas');
        const img = document.createElement('img');
        img.src = reader.result as string;
        img.onload = () => {
          const ctx = canvas.getContext('2d');
          const _dWH = this.dWH(img.width, img.height, this.maxWH);
          canvas.width = _dWH.width;
          canvas.height = _dWH.height;

          if (ctx) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          }

          const newImgData = canvas.toDataURL(fileType, 0.9);
          const blob = this.dataURLtoBlob(newImgData, fileType);
          const nfile = new File([blob], this.file.name);
          resolve(nfile);
        };
      };
    });
  }

  dWH(srcW: number, srcH: number, dMax: number) {
    const defaults = {
      width: srcW,
      height: srcH,
    };
    if (Math.max(srcW, srcH) > dMax) {
      if (srcW > srcH) {
        defaults.width = dMax;
        defaults.height = Math.round(srcH * (dMax / srcW));
        return defaults;
      } else {
        defaults.height = dMax;
        defaults.width = Math.round(srcW * (dMax / srcH));
        return defaults;
      }
    } else {
      return defaults;
    }
  }

  fileSizeKB(dataURL: string) {
    let sizeKB = 0;
    sizeKB = Math.round((dataURL.split(',')[1].length * 3) / 4 / 1024);
    return sizeKB;
  }

  dataURLtoBlob(dataURL: string, fileType?: string) {
    const byteString = atob(dataURL.split(',')[1]);
    let mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    if (fileType) {
      mimeString = fileType;
    }
    return new Blob([ab], { type: mimeString });
  }
}

const path = (typeof window !== 'undefined' && (window as any).__VITE_FILE_API__) || '';

export const getUrl = (url: string) => {
  if (url && url.slice(0, 4) !== 'http') {
    if (path === '/') {
      return url;
    }
    if (url.slice(0, 1) === '/') {
      return path + url;
    }
    return path + '/' + url;
  } else {
    return url;
  }
};

const VIDEO_EXTENSIONS = ['.mp4', '.mov', '.webm', '.ogg'];
const VIDEO_MIME_TYPES = ['video/mp4', 'video/webm', 'video/ogg'];
const IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml'];

export const isVideoExt = (url: string) => {
  const urlLower = url?.toLowerCase() || '';
  return urlLower !== '' && VIDEO_EXTENSIONS.some((ext) => urlLower.endsWith(ext));
};

export const isVideoMime = (type: string) => {
  const typeLower = type?.toLowerCase() || '';
  return typeLower !== '' && VIDEO_MIME_TYPES.includes(typeLower);
};

export const isImageMime = (type: string) => {
  const typeLower = type?.toLowerCase() || '';
  return typeLower !== '' && IMAGE_MIME_TYPES.includes(typeLower);
};
