"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateAsset = exports.durationToMilliseconds = exports.downloadAsset = exports.catchAndLogError = void 0;

var _axios = _interopRequireDefault(require("axios"));

var _dateFns = require("date-fns");

var _fsExtra = require("fs-extra");

var _path = _interopRequireDefault(require("path"));

var _sharp = _interopRequireDefault(require("sharp"));

var _config = require("./config");

var _image = require("./entity/image");

var _logger = require("./logger");

var _image2 = require("./repository/image");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const durationToMilliseconds = duration => (0, _dateFns.add)(0, duration).getTime();

exports.durationToMilliseconds = durationToMilliseconds;

const downloadAsset = async args => {
  const {
    imageId,
    url
  } = args;

  const imagePath = _path.default.resolve(_config.Config.ASSETS_PATH, 'original', `${imageId}.webp`);

  const imageSmallPath = _path.default.resolve(_config.Config.ASSETS_PATH, 'small', `${imageId}.webp`);

  const response = await _axios.default.get(url, {
    responseType: 'arraybuffer'
  });
  await (0, _fsExtra.ensureDir)(_path.default.dirname(imagePath));
  await (0, _sharp.default)(response.data).resize({
    width: 800
  }).webp({
    quality: 80
  }).toFile(imagePath);
  await (0, _fsExtra.ensureDir)(_path.default.dirname(imageSmallPath));
  await (0, _sharp.default)(response.data).resize({
    width: 400
  }).webp({
    quality: 80
  }).toFile(imageSmallPath);
};

exports.downloadAsset = downloadAsset;

const updateAsset = async args => {
  const {
    mediaItemId,
    url,
    seasonId,
    type
  } = args;
  const oldPoster = await _image2.imageRepository.findOne({
    mediaItemId: mediaItemId,
    seasonId: seasonId || null,
    type: type
  });
  const newImageId = (0, _image.getImageId)();
  await downloadAsset({
    imageId: newImageId,
    url: url
  });

  if (oldPoster) {
    await _image2.imageRepository.updateWhere({
      value: {
        id: newImageId
      },
      where: {
        id: oldPoster.id
      }
    });
    const imagePath = `/img/original/${oldPoster.id}`;

    if (await (0, _fsExtra.pathExists)(imagePath)) {
      await (0, _fsExtra.rm)(imagePath);
    }

    const smallImagePath = `/img/original/${oldPoster.id}`;

    if (await (0, _fsExtra.pathExists)(smallImagePath)) {
      await (0, _fsExtra.rm)(smallImagePath);
    }
  } else {
    await _image2.imageRepository.create({
      id: newImageId,
      mediaItemId: mediaItemId,
      seasonId: seasonId || null,
      type: type
    });
  }
};

exports.updateAsset = updateAsset;

const catchAndLogError = async fn => {
  try {
    await fn();
  } catch (error) {
    _logger.logger.error(error);
  }
};

exports.catchAndLogError = catchAndLogError;
//# sourceMappingURL=utils.js.map