// gab-tv.js
// Copyright (C) 2021 Digital Telepresence, LLC
// License: Apache-2.0

'use strict';

const fetch = require('node-fetch'); // jshint ignore:line

const CACHE_DURATION = 60 * 5;

const { SiteService } = require('../../lib/site-lib');

class GabTVService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  channelMiddleware ( ) {
    return async (req, res, next) => {
      try {
        if (!res.locals.site || !res.locals.site.gabtvUrl) {
          return next();
        }
        this.log.debug('GabTV URL', { url: res.locals.site.gabtvUrl });
        const urlParts = res.locals.site.gabtvUrl.split('/');
        const channelSlug = urlParts[urlParts.length - 1];
        res.locals.gabTvChannel = await this.getChannelEpisodes(channelSlug, { allowCache: true });
        return next();
      } catch (error) {
        this.log.error('failed to populdate Gab TV channel', { error });
        return next();
      }
    };
  }

  async getChannelEpisodes (channelSlug, options) {
    const { cache: cacheService } = this.dtp.services;
    const cacheKey = `gabtv:ch:${channelSlug}`;

    options = Object.assign({
      allowCache: true,
    }, options);

    let json;
    if (options.allowCache) {
      json = await cacheService.getObject(cacheKey);
      if (json) {
        return json;
      }
    }

    const response = await fetch(`https://tv.gab.com/channel/${channelSlug}/feed/json`);
    json = await response.json();

    await cacheService.setObjectEx(cacheKey, CACHE_DURATION, json);

    return json;
  }
}

module.exports = {
  slug: 'gab-tv',
  name: 'gabTV',
  create: (dtp) => { return new GabTVService(dtp); },
};