import axios from 'axios';
import { v4 as uuid } from 'uuid';
import { Message } from 'eris';
import { Client, Command } from '../class';

export default class TTS extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'tts';
    this.description = 'Uses Google Text to Speech engines to synthesize input to a MP3 file. Only supports English at this time.';
    this.usage = `${this.client.config.prefix}tts <text>`;
    this.permissions = 0;
    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]);
      if (args.length > 200) return this.error(message.channel, 'Cannot synthesize more than 200 characters.');
      const msg = await this.loading(message.channel, 'Synthesizing...');
      const d = await axios({
        method: 'GET',
        url: `https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=${encodeURIComponent(args.join(' '))}&tl=en`,
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
        },
        responseType: 'arraybuffer',
      });
      msg.delete();
      return message.channel.createMessage(undefined, { name: `${uuid()}.mp3`, file: d.data });
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
