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

async function generateIcon(
  photoPath: string,
  size: number,
  outputPath: string,
) {
  await sharp(photoPath)
    .resize(size, size, {
      fit: 'cover',
      position: 'center',
    })
    .toFile(outputPath);
}

export async function generateManifest(shooting: Shooting) {
  const frontSite = process.env.FRONT_SITE;
  const originSite = process.env.ORIGIN_SITE;
  const uploadPath = path.resolve(
    process.env.UPLOAD_PATH || __dirname,
    `shootings/${shooting.id}`,
  );

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

  const orderedPhotos = shooting.photos.sort((a, b) => a.order - b.order);
  const firstPhoto = orderedPhotos[0];

  if (firstPhoto) {
    const photoPath = path.join(uploadPath, firstPhoto.filename);
    const icon192Path = path.join(uploadPath, 'icon-192x192.png');
    const icon512Path = path.join(uploadPath, 'icon-512x512.png');

    await generateIcon(photoPath, 192, icon192Path);
    await generateIcon(photoPath, 512, icon512Path);
  }

  const manifestContent = {
    name: `${shooting.name}`,
    short_name: `${shooting.name}`,
    description: `Photos du shooting ${shooting.name}`,
    start_url: `${frontSite}/shootings/${shooting.id}/view?customerId=${shooting.customerId}&mode=customer`,
    display: 'standalone',
    background_color: '#ffffff',
    theme_color: '#ffffff',
    icons: [
      {
        src: firstPhoto
          ? `${originSite}/photos/${shooting.id}/icon-192x192.png`
          : `${originSite}/pwa-192x192.png`,
        sizes: '192x192',
        type: 'image/png',
      },
      {
        src: firstPhoto
          ? `${originSite}/photos/${shooting.id}/icon-512x512.png`
          : `${originSite}/pwa-512x512.png`,
        sizes: '512x512',
        type: 'image/png',
      },
    ],
  };

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

  fs.writeFileSync(
    customerManifestPath,
    JSON.stringify(manifestContent, null, 2),
  );

  const guestManifest = {
    ...manifestContent,
    start_url: `${frontSite}/shootings/${shooting.id}/view?customerId=${shooting.customerId}&mode=guest`,
  };
  fs.writeFileSync(guestManifestPath, JSON.stringify(guestManifest, null, 2));

  return {
    customer: manifestContent,
    guest: guestManifest,
  };
}
