"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ProgressController = void 0;

var _typescriptRoutesToOpenapiServer = require("typescript-routes-to-openapi-server");

var _episode = require("../repository/episode");

var _mediaItem = require("../repository/mediaItem");

var _seen = require("../repository/seen");

var _listItemRepository = require("../repository/listItemRepository");

/**
 * @openapi_tags Progress
 */
class ProgressController {
  /**
   * @openapi_operationId add
   */
  add = (0, _typescriptRoutesToOpenapiServer.createExpressRoute)(async (req, res) => {
    const userId = Number(req.user);
    const {
      mediaItemId,
      episodeId,
      date,
      action,
      duration,
      progress
    } = req.query;

    if (progress != undefined && (progress < 0 || progress > 1)) {
      res.status(400);
      res.send('Progress should be between 0 and 1');
      return;
    }

    const mediaItem = await _mediaItem.mediaItemRepository.findOne({
      id: mediaItemId
    });

    if (!mediaItem || mediaItem.mediaType === 'tv') {
      res.send(400);
      return;
    }

    if (episodeId) {
      const episode = await _episode.tvEpisodeRepository.findOne({
        id: episodeId
      });

      if (!episode) {
        res.send(400);
        return;
      }
    }

    await _seen.seenRepository.create({
      userId: userId,
      action: action,
      type: 'progress',
      date: date,
      duration: duration,
      episodeId: episodeId,
      mediaItemId: mediaItemId,
      progress: progress
    });

    if (progress === 1 && episodeId == undefined) {
      await _listItemRepository.listItemRepository.removeItem({
        userId: userId,
        mediaItemId: mediaItemId,
        watchlist: true
      });
      await _seen.seenRepository.create({
        userId: userId,
        action: action,
        type: 'seen',
        date: date,
        duration: duration,
        episodeId: episodeId,
        mediaItemId: mediaItemId,
        progress: progress
      });
    } else {
      await _listItemRepository.listItemRepository.addItem({
        userId: userId,
        mediaItemId: mediaItemId,
        watchlist: true
      });
    }

    res.send();
  });
  /**
   * @openapi_operationId deleteById
   */

  deleteById = (0, _typescriptRoutesToOpenapiServer.createExpressRoute)(async (req, res) => {
    const {
      progressId
    } = req.params;
    await _seen.seenRepository.delete({
      id: progressId
    });
    res.send();
  });
}

exports.ProgressController = ProgressController;
//# sourceMappingURL=progress.js.map