import { Jimp } from 'jimp';
import random from 'random';

export const wartermarkConfig = {
  productImage: 'https://cdn.autoshopee.com/uploads/extension-kit/images/khung-anh-san-pham.png',
  noImage: 'https://cdn.autoshopee.com/uploads/extension-kit/images/upload-khung-btn.png',
};

/**
 *
 * @param {string} base4Image
 * @returns {string}
 */
export const extractBas64Image = (base4Image) => {
  return base4Image.replace('data:image/jpeg;base64,', '');
};

/**
 *
 * @param {string} base4Image
 * @returns {string}
 */
export const appendBase64Image = (base4Image) => {
  return `data:image/jpeg;base64,${base4Image}`;
};
/**
 *
 * @param {string} base64Image
 * @returns {Promise<Blob>}
 */
export const base64ImageToBlob = (base64Image) => {
  const base64Data = base64Image.split(',')[1];
  const binaryString = atob(base64Data);
  const uint8Array = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    uint8Array[i] = binaryString.charCodeAt(i);
  }

  return new Blob([uint8Array], { type: 'image/jpeg' });
};

/**
 *
 * @param {string} imageUrl
 * @returns {Promise<Blob>}
 */
export const changeImageMd5 = async (imageUrl) => {
  const jimpSource = await Jimp.read(imageUrl);

  const pixelCount = random.int(5, 12);
  for (let i = 0; i < pixelCount; i++) {
    const randomX = random.int(0, jimpSource.width - 1);
    const randomY = random.int(0, jimpSource.height - 1);
    const currentColor = jimpSource.getPixelColor(randomX, randomY);
    const colorChange = random.int(1, 15);
    const newColor = Math.min(currentColor + colorChange, 0xFFFFFFFF);
    jimpSource.setPixelColor(newColor, randomX, randomY);
  }

  const watermarkSize = random.int(1, 3);
  const watermarkX = random.int(0, jimpSource.width - watermarkSize);
  const watermarkY = random.int(0, jimpSource.height - watermarkSize);

  const watermarkColor = 0x00000000 + random.int(1, 10);
  for (let x = 0; x < watermarkSize; x++) {
    for (let y = 0; y < watermarkSize; y++) {
      jimpSource.setPixelColor(watermarkColor, watermarkX + x, watermarkY + y);
    }
  }

  return jimpSource.getBase64('image/jpeg');
};

/**
 *
 * @param {string} imageUrl
 * @returns {Promise<{width: number, height: number}>}
 */
export const getImageSize = async (imageUrl) => {
  const jimpSource = await Jimp.read(imageUrl);
  return {
    width: jimpSource.width,
    height: jimpSource.height,
  };
};

/**
 *
 * @param {string} imageUrlSource
 * @param {string} imageUrlLayer
 * @param {object} layerSize
 * @returns {Promise<Blob>}
 */
export const watermarkImageFrame = async (
  imageUrlSource,
  imageUrlLayer,
  layerSize = {
    width: 0,
    height: 0,
  },
) => {
  const [jimpSource, jimpLayer] = await Promise.all([
    Jimp.read(imageUrlSource),
    Jimp.read(imageUrlLayer),
  ]);

  jimpSource.resize({ w: layerSize.width, h: layerSize.height });

  jimpSource.composite(jimpLayer, 0, 0);

  return jimpSource.getBase64('image/jpeg');
};
