/* eslint-disable consistent-return */
import ARI from 'ari-client';
import { TextableChannel } from 'eris';
import PageCommand from '../../commands/page';
import { Handler, PBX } from '../../class';
import { Misc } from '..';

export default class PageDTMF extends Handler {
  constructor(pbx: PBX) {
    super(pbx);
    this.app = 'page-dtmf';
    this.options.available = true;
  }

  public async run(event: ARI.Event, channel: ARI.Channel) {
    if (event.application !== 'page-dtmf') return;
    const message = await (<TextableChannel> this.client.guilds.get(this.client.config.guildID).channels.get('501089664040697858')).getMessage('775604192013320203');
    if (!message) return Misc.accessDenied(channel);
    const member = await this.client.db.Staff.findOne({ extension: channel.caller.number }).lean().exec();
    if (!member) return Misc.accessDenied(channel);
    const pager = await this.client.db.PagerNumber.findOne({ individualAssignID: member.userID }).lean().exec();
    if (!pager) return Misc.accessDenied(channel);
    let status = 0;
    const pagerNumber: string[] = [];
    const pagerCode: string[] = [];
    channel.answer();
    const pnPlaybackC = this.pbx.ari.Playback();
    channel.play({
      media: 'sound:please-enter-the-pn',
    }, pnPlaybackC);
    channel.on('ChannelDtmfReceived', async (ev) => {
      if (!channel.connected) return;
      if (status === 0) {
        if (ev.digit === '#') {
          pnPlaybackC.stop().catch(() => {});
          await channel.play({
            media: 'sound:please-enter-the-pc',
          }, undefined);
          status = 1;
          return null;
        }
        pagerNumber.push(ev.digit);
      } else if (status === 1) {
        const processingPlayback = this.pbx.ari.Playback();
        if (ev.digit === '#') {
          await channel.play({
            media: 'sound:pls-hold-process-tx',
          }, processingPlayback);

          const Page = <PageCommand> this.client.commands.get('page');
          const page = await Page.page(pagerNumber.join(''), pager.num, pagerCode.join(''), message);
          if (page.status === true) {
            processingPlayback.stop();
            await Misc.play(this.pbx, channel, 'sound:page-delivered');
            channel.hangup();
          } else if (page.status === false) {
            try {
              const ch = await this.client.getDMChannel(member.userID);
              if (ch) {
                ch.createMessage(`***An error has occurred while trying to process your page request over the PBX.***\n*${page.message}*\n\nPlease check your parameters and try again.`);
              }
            } catch {
              this.client.util.handleError(new Error(page.message));
            }
            processingPlayback.stop();
            await Misc.play(this.pbx, channel, 'sound:request-error');
            channel.hangup();
          }
          return null;
        }
        pagerCode.push(ev.digit);
      }
    });
  }
}
