import fetch from "flumm-fetch";
import { exec as _exec } from "child_process";
import fs from "fs";
import db from "./sql.mjs";

export default new class queue {

  constructor() {

  };

  addqueue(e, link) {
    //this.#queue.push(e, link);
  };

  exec(cmd) {
    return new Promise((resolve, reject) => {
      _exec(cmd, { maxBuffer: 5e3 * 1024 }, (err, stdout, stderr) => {
        if(err)
          return reject(err);
        if(stderr)
          console.error(stderr);
        resolve({ stdout: stdout });
      });
    });
  };

  async genuuid() {
    return (await db`
      select gen_random_uuid() as uuid
    `)[0].uuid.substring(0, 8);
  };

  async checkrepostlink(link) {
    const q_repost = await db`
      select id
      from "items"
      where src = ${link}
    `;
    return q_repost.length > 0 ? q_repost[0].id : false;
  };

  async checkrepostsum(checksum) {
    const q_repost = await db`
      select id
      from "items"
      where checksum = ${checksum}
    `;
    return q_repost.length > 0 ? q_repost[0].id : false;
  };

  async getItemID(filename) {
    return (await db`
      select *
      from "items"
      where dest = ${filename}
      limit 1
    `)[0].id;
  };

  async genThumbnail(filename, mime, itemid, link) {
    if(mime.startsWith('video/') || mime == 'image/gif')
      await this.exec(`ffmpegthumbnailer -i./public/b/${filename} -s1024 -o./tmp/${itemid}.png`);
    else if(mime.startsWith('image/') && mime != 'image/gif')
      await this.exec(`magick "./public/b/${filename}[0]" ./tmp/${itemid}.png`);
    else if(mime.startsWith('audio/')) {
      if(link.match(/soundcloud/)) {
        let cover = (await this.exec(`yt-dlp -f 'bv*[height<=720]+ba/b[height<=720] / wv*+ba/w' --get-thumbnail "${link}"`)).stdout.trim();
        if(!cover.match(/default_avatar/)) {
          cover = cover.replace(/-(large|original)\./, '-t500x500.');
          try {
            await this.exec(`wget "${cover}" -O ./tmp/${itemid}.jpg`);
            const size = (await fs.promises.stat(`./tmp/${itemid}.jpg`)).size;
            if(size >= 0) {
              await this.exec(`magick ./tmp/${itemid}.jpg ./tmp/${itemid}.png`);
              await this.exec(`magick ./tmp/${itemid}.jpg ./public/ca/${itemid}.webp`);
            }
          } catch(err) {}
        }
        else {
          await this.exec(`ffmpeg -i ./public/b/${filename} -update 1 -map 0:v -map 0:1 -c copy ./tmp/${itemid}.png`);
          await this.exec(`magick ./tmp/${itemid}.png ./public/ca/${itemid}.webp`);
        }
      }
      else {
        await this.exec(`ffmpeg -i ./public/b/${filename} -update 1 -map 0:v -map 0:1 -c copy ./tmp/${itemid}.png`);
        await this.exec(`magick ./tmp/${itemid}.png ./public/ca/${itemid}.webp`);
      }
    }

    await this.exec(`magick "./tmp/${itemid}.png" -resize "128x128^" -gravity center -crop 128x128+0+0 +repage ./public/t/${itemid}.webp`);
    await fs.promises.unlink(`./tmp/${itemid}.png`).catch(_=>{});
    await fs.promises.unlink(`./tmp/${itemid}.jpg`).catch(_=>{});
    return true;
  };

  // tags
  async tagSFW(itemid) {
    return await db`
      insert into "tags_assign" ${
        db({
          item_id: itemid,
          tag_id: 1,
          user_id: 1
        })
      }
    `;
  };

  async tagNSFW(itemid) {
    return await db`
      insert into "tags_assign" ${
        db({
          item_id: itemid,
          tag_id: 2,
          user_id: 1
        })
      }
    `;
  };

};
