import sql from "../src/inc/sql.mjs";
import fs from "fs";
import { exec as _exec } from "child_process";

const exec = cmd => 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 });
  });
});

const _args = process.argv.slice(2);
const _itemid = +_args[0] || 0;

let items;
if(_itemid > 0)
  items = await sql('items').where('id', _itemid);
else
  items = await sql`select id, dest, mime, src from "items"`;
let count = 1;
let total = items.length;

for(let item of items) {
  const itemid = item.id;
  const filename = item.dest;
  const mime = item.mime;
  const link = item.src;
  try {
    if(mime.startsWith('video/') || mime == 'image/gif')
      await exec(`ffmpegthumbnailer -i./public/b/${filename} -s1024 -o./tmp/${itemid}.png`);
    else if(mime.startsWith('image/') && mime != 'image/gif')
      await exec(`magick ./public/b/${filename} ./tmp/${itemid}.png`);
    else if(mime.startsWith('audio/')) {
      if(link.match(/soundcloud/)) {
        let cover = (await exec(`yt-dlp --get-thumbnail "${link}"`)).stdout.trim();
        if(!cover.match(/default_avatar/)) {
          cover = cover.replace(/-(large|original)\./, '-t500x500.');
          try {
            await exec(`wget "${cover}" -O ./tmp/${itemid}.jpg`);
            const size = (await fs.promises.stat(`./tmp/${itemid}.jpg`)).size;
            if(size >= 0) {
              await exec(`magick ./tmp/${itemid}.jpg ./tmp/${itemid}.png`);
              await exec(`magick ./tmp/${itemid}.jpg ./public/ca/${itemid}.webp`);
            }
          } catch(err) {
            //console.log(err);
          }
        }
        else {
          await exec(`ffmpeg -i ./public/b/${filename} -update 1 -map 0:v -map 0:1 -c copy ./tmp/${itemid}.png`);
          await exec(`magick ./tmp/${itemid}.png ./public/ca/${itemid}.webp`);
        }
      }
      else {
        await exec(`ffmpeg -i ./public/b/${filename} -update 1 -map 0:v -map 0:1 -c copy ./tmp/${itemid}.png`);
        await exec(`magick ./tmp/${itemid}.png ./public/ca/${itemid}.webp`);
      }
    }

    await 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(err => {});
    await fs.promises.unlink(`./tmp/${itemid}.jpg`).catch(err => {});
  } catch(err) {
    //console.log(err);
    await exec(`magick ./mugge.png ./public/t/${itemid}.webp`);
  }
  console.log(`current: ${itemid} (${count} / ${total})`);
  count++;
}

/*for(let item of items) {
  try {
    const itemid = item.id;
    const filename = item.dest;
    await exec(`ffmpegthumbnailer -i./public/b/${filename} -s1024 -o./debug/tmp/${itemid}`);
    await exec(`magick "./debug/tmp/${itemid}" -resize "128x128^" -gravity center -crop 128x128+0+0 +repage ./public/t/${itemid}.png`);
    await fs.unlink(`./debug/tmp/${itemid}`);
    console.log(`current: ${itemid} (${count} / ${total})`);
  } catch(err) {}
  count++;
};*/
