var express = require('express');
var router = express.Router();
const fs = require('fs');
var path = require('path');
const createError = require('http-errors');
const config = require('../../config/app');
const { makeThumb } = require('../../libs/image');


router.get(/^\/(avatar)\/(128|256|512|480|320|640|720)\/([a-f0-9]{24}).(png|jpg|jpeg|webp)$/, function (req, res, next) {
  (async function () {
    let params = Object.values(req.params);
    let [type, size, id, ext] = params;
    var staticRoot = config.STATIC_DIR;
    var thumbFilePath = path.resolve(staticRoot, 'thumbs/v1', [type, size, id].join('/')) + '.' + ext;
    var originalFilePath = path.resolve(staticRoot, 'thumbs/v1', [type, 'original', id].join('/')) + '.' + ext;
    let exists = fs.existsSync(originalFilePath);
    let dir;
    if (!exists) {
      let data;
      if (type == 'avatar') {
        try {
          data = fs.readFileSync(__dirname + `/../../dist/assets/avatar/${id}.jpeg`);
        } catch (e) {
          if (!data) data = fs.readFileSync(__dirname + `/../../dist/assets/avatar/default.jpeg`);
        }
      }

      if (!data) throw createError(404, 'Page not found');

      dir = path.dirname(originalFilePath);
      fs.mkdirSync(dir, { recursive: true });

      fs.writeFileSync(originalFilePath, data)
    }

    dir = path.dirname(thumbFilePath);
    fs.mkdirSync(dir, { recursive: true });
    await makeThumb(originalFilePath, thumbFilePath, size);

    res.sendFile(thumbFilePath);
  })().catch(next)
});



module.exports = router;
