import QRCode from 'qrcode';
import axios from 'axios';
import Jimp from 'jimp';

const downloadAndProcessImage = async (url: string)=> {
    try {
      const response = await axios({
        method: 'get',
        url: url,
        responseType: 'arraybuffer',
      });
  
      const buffer = Buffer.from(response.data);
      const image = await Jimp.read(buffer);
      image.resize(512, 512).circle({ radius: 256 });
  
      return image;
    } catch (err) {
      console.error('Error al descargar la imagen:', err);
      throw err;
    }
  };

  const generateLogoCircle = async (url: string) => {
  try {
        const lenna = await downloadAndProcessImage(url);

        const borderWidth = lenna.bitmap.width * 0.1;

        const original_width = lenna.bitmap.width;
        const original_height = lenna.bitmap.height;

        const new_width = original_width < original_height ? original_height : original_width;
        const new_height = original_height < original_width ? original_width : original_height;

        // Create a new image with the size increased to include the frame
        const circle_image = new Jimp(
            new_width + 2 * borderWidth,
            new_height + 2 * borderWidth,
            0xFFFFFFFF
        );

        const x = (new_width - original_width) / 2;
        const y = (new_height - original_height) / 2;

        // Paste the original image in the center of the new image with the frame
        if (original_width === original_height) {
            circle_image.composite(lenna, borderWidth, borderWidth);
        } else {
            circle_image.composite(lenna, x, y);
        }

        // Create the circle in the new image
        circle_image.circle({
            radius: circle_image.bitmap.width / 2 - circle_image.bitmap.width * 0.00,
            antialias: true,
            
        }).quality(100);

        const img=await circle_image.resize(64, 64).circle({ radius: circle_image.bitmap.width / 2 });
        return img;
  } catch (err) {
      console.error('Error en el proceso:', err);
      throw err;
  }
};



const generateQr = async (text: string, url_icon: string) => {


    const url = await new Promise<string>((resolve, reject) => {
        QRCode.toDataURL(text, { width: 512 }, (err: any, url: string) => {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                resolve(url);
            }
        });
    });

    // Procesamiento posterior utilizando la URL obtenida
    const base64_data = url.replace(/^data:image\/png;base64,/, '');
    const qrImage = await Jimp.read(Buffer.from(base64_data, 'base64'));

    const iconImage = await generateLogoCircle(url_icon);
    const x = Math.floor((512 - 64) / 2);
    const y = Math.floor((512 - 64) / 2);
    qrImage.composite(iconImage, x, y);
    return qrImage;
};


export const generateSms = async (number: number, sms: string, url_icon: string) => {
    const text = "SMSTO:" + number + ":" + sms;
    const image=await generateQr(text, url_icon);
    return image;
};

export const generateUrl = async (url: string, url_icon: string) => {
    const image = await generateQr(url, url_icon);
    return image;
};

export const generateTextPlain = async (text:string, url_icon: string) => {
    const image=await generateQr(text, url_icon);
    return image;
}

export const generateEmail = async (to:string, subject:string, body:string, url_icon: string) => {
    const text="MATMSG:TO:"+to+";SUB:"+subject+";BODY:"+body+"send;;"
    const image=await generateQr(text, url_icon);
    return image;
}

export const generateWifi = async (name:string, password:string, url_icon: string) => {
    const text = "WIFI:T:WPA;S:" + name + ";P:" + password + ";;";
    const image=await generateQr(text, url_icon);
    return image;
}

export const generateContact = async (name:string, telephone: number, email:string, company:string, address:string, website:string, url_icon: string) => {
    var text = "";
    text += "BEGIN:VCARD\nVERSION:3.0\nN:"+name?name:''+"\nTEL:"+telephone?telephone:''+"\nEMAIL:"+email?email:''+"\nORG:"+company?company:''+"\nADR:"+address?address:''+"\nURL:"+website?website:''+"\nEND:VCARD";
    const image=await generateQr(text, url_icon);
    return image;
}