import { Message, TextChannel } from 'eris';
import { Client, Command } from '../class';

export default class Train extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'train';
    this.description = 'Trains a neural network.';
    this.usage = `${this.client.config.prefix}train <channel> <message id> <1: good | 0: bad>`;
    this.permissions = 1;
    this.guildOnly = false;
    this.enabled = false;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (args?.length < 3) return this.client.commands.get('help').run(message, [this.name]);
      if (args[2] !== '0' && args[2] !== '1') return this.error(message.channel, 'Result must be either 0 or 1.');
      const channel = <TextChannel> this.client.util.resolveGuildChannel(args[0], this.mainGuild);
      if (!channel) return this.error(message.channel, 'Channel could not be found.');
      if (channel.type !== 0) return this.error(message.channel, 'Invalid channel type.');
      let msg: Message;
      try {
        msg = await channel.getMessage(args[1]);
      } catch {
        return this.error(message.channel, 'Could not find message.');
      }
      if (!msg) return this.error(message.channel, 'Message could not be found.');

      await this.client.db.NNTrainingData.updateOne({ name: 'tc' }, { $addToSet: { data: { input: this.client.util.encode(msg.content), output: { res: Number(args[2]) } } } });
      await message.delete();
      const done = await this.success(message.channel, 'Neural Network trained successfully.');
      return setTimeout(async () => {
        await done.delete();
      }, 3000);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
