import { Message } from 'eris';
import { Client, Command } from '../class';
import { Misc as MiscPBXActions } from '../pbx';

export default class Intercom extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'intercom';
    this.description = 'Will synthesize inputted text to a recording and dial an intercom to the extension specified, then play the recording.';
    this.usage = `${this.client.config.prefix}intercom <extension> <text>`;
    this.permissions = 1;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
      const loading = await this.loading(message.channel, 'Synthesizing text...');

      const recordingLocation = await MiscPBXActions.TTS(this.client.util.pbx, `Hello, this is the Library of Code Private Branch Exchange dialing you at the request of ${message.author.username} to deliver you a message. Playing message: ${args.slice(1).join(' ')}`, 'MALE');
      await loading.edit(`***${this.client.util.emojis.LOADING} Preparing to dial...***`);
      this.client.util.pbx.ami.action({
        action: 'originate',
        channel: `PJSIP/${args[0]}`,
        exten: args[0],
        context: 'from-internal',
        CallerID: `TTS INTC FRM ${message.author.username} <000>`,
        application: 'PlayBack',
        priority: '1',
        data: `beep&${recordingLocation.split(':')[1]}`,
        variable: {
          'PJSIP_HEADER(add,Call-Info)': '<uri>;answer-after=0',
          'PJSIP_HEADER(add,Alert-Info)': 'Ring Answer',
        },
      }, async (err: Error) => {
        if (err) return loading.edit(`***${this.client.util.emojis.ERROR} Failed to dial extension.***`);
        return loading.edit(`***${this.client.util.emojis.SUCCESS} Successfully queued intercom message to EXT \`${args[0]}\`.***`);
      });
      return undefined;
    } catch (err) {
      return this.client.util.handleError(err, message, this, false);
    }
  }
}
