// venue/cron/update-channel-status.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const path = require('path');

const mongoose = require('mongoose');
const VenueChannel = mongoose.model('VenueChannel');

const { CronJob } = require('cron');

const { SiteWorkerProcess } = require(path.join(__dirname, '..', '..', '..', '..', 'lib', 'site-lib'));

class UpdateChannelStatusCron extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'updateChannelStatus',
      slug: 'update-channel-status',
    };
  }

  constructor (worker) {
    super(worker, UpdateChannelStatusCron.COMPONENT);
  }

  async start ( ) {
    await super.start();

    await this.updateChannelStatus(); // first-run the expirations

    this.job = new CronJob(
      '*/15 * * * * *',
      this.updateChannelStatus.bind(this),
      null,
      true,
      process.env.DTP_CRON_TIMEZONE || 'America/New_York',
    );
  }

  async stop ( ) {
    if (this.job) {
      this.log.info('stopping channel update job');
      this.job.stop();
      delete this.job;
    }
    await super.stop();
  }

  async updateChannelStatus ( ) {
    const { venue: venueService } = this.dtp.services;
    try {
      await VenueChannel
        .find()
        .lean()
        .cursor()
        .eachAsync(async (channel) => {
          this.log.info('updating channel status', { channel: channel.slug });
          const status = await venueService.updateChannelStatus(channel);
          this.log.info('channel status updated', { channel: status.name, status: status.status });
        });
    } catch (error) {
      this.log.error('failed to expire crashed hosts', { error });
    }
  }
}

module.exports = UpdateChannelStatusCron;