// resource route component
import React from "react";
import { PassThrough } from "node:stream"
import fs from "node:fs"
import {createReadableStreamFromReadable} from "@remix-run/node"
import { defaultQuality,widths,mainImageReadStream,generatedImageReadstream, isThereImage,BadImageResponse } from "../../util/image.server"

export const loader = async ({ request }) => {
  const url = new URL(request.url);
  const src = url.searchParams.get("src");
  const width = url.searchParams.get("w");
  if (!src || !width ) {
    return BadImageResponse();
  }
  try{
    if(!await isThereImage(src)) {
      for (const width of widths) {
        await generatedImageReadstream(await mainImageReadStream(src),src,width,defaultQuality)
      }
    } else {
      const {size,fileStream,hash} = await generatedImageReadstream(await mainImageReadStream(src),src,width,defaultQuality)
      const body = new PassThrough()
      const stream = fileStream
      stream.on('error', err => body.end(err))
      stream.on('end', () => body.end())
      stream.pipe(body) 
      return new Response(createReadableStreamFromReadable(body), {
        status: 200,
        headers: {
          'content-type': 'image/webp',
          'content-length': String(size),
          'content-disposition': `inline; filename="${hash}.webp"`,
          'cache-control': 'public, max-age=31536000, immutable',
        },
      })
    }
  } catch(e) {
    console.log(e)
    return BadImageResponse();
  }
}

/* 
 # tnx to
  - https://github.com/ccssmnn : https://github.com/remix-run/remix/discussions/2905#discussioncomment-2596810
  - https://stackoverflow.com/a/51302466/12814525
  - https://github.com/epicweb-dev/web-forms
*/