import * as path from 'path';
import * as fs from 'fs';
import * as sharp from 'sharp';
import { Customer } from '../domain/Customer';

async function generateIcon(
  photoPath: string,
  size: number,
  outputPath: string,
) {
  const outputDir = path.dirname(outputPath);

  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  await sharp(photoPath)
    .resize(size, size, {
      fit: 'contain',
      position: 'center',
      background: { r: 0, g: 0, b: 0, alpha: 0 },
    })
    .png({ quality: 100 })
    .toFile(outputPath);
}

export async function generateManifestCustomer(customer: Customer) {
  try {
    const frontSite = process.env.FRONT_SITE;
    const originSite = process.env.ORIGIN_SITE;
    const customerId = customer.id;
    const uploadPath = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      `customers/${customerId}`,
    );

    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }

    const baseIconPath = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      'app/icons/icon.png',
    );

    const icon192Path = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      'app/icons/icon-192x192.png',
    );

    const icon512Path = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      'app/icons/icon-512x512.png',
    );

    await generateIcon(baseIconPath, 192, icon192Path);
    await generateIcon(baseIconPath, 512, icon512Path);

    const manifestContent = {
      name: `Mes Galeries`,
      short_name: `Mes Galeries`,
      description: `Galerie photos de ${customer.firstname} ${customer.lastname}`,
      start_url: `${frontSite}/my-shootings/${customerId}?customerId=${customerId}&mode=customer`,
      display: 'standalone',
      background_color: '#ffffff',
      theme_color: '#ffffff',
      scope: `${frontSite}/my-shootings/${customerId}`,
      icons: [
        {
          src: `${originSite}/files/app/icons/icon-192x192.png`,
          sizes: '192x192',
          type: 'image/png',
        },
        {
          src: `${originSite}/files/app/icons/icon-512x512.png`,
          sizes: '512x512',
          type: 'image/png',
        },
      ],
    };

    const customerManifestPath = path.join(uploadPath, 'customer.webmanifest');
    const guestManifestPath = path.join(uploadPath, 'guest.webmanifest');

    await fs.promises.writeFile(
      customerManifestPath,
      JSON.stringify(manifestContent, null, 2),
      'utf-8',
    );

    const guestManifest = {
      ...manifestContent,
      start_url: `${frontSite}/my-shootings/${customerId}?customerId=${customerId}&mode=guest`,
    };

    await fs.promises.writeFile(
      guestManifestPath,
      JSON.stringify(guestManifest, null, 2),
      'utf-8',
    );

    return {
      customer: manifestContent,
      guest: guestManifest,
    };
  } catch (error) {
    console.error(error);
  }
}
