import { Message } from 'eris';
import stockInfo from 'stock-info';
import { Client, Command, RichEmbed } from '../class';

export default class Market extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'market';
    this.description = 'Fetches information from a ticker for a stock or fund.';
    this.usage = `${this.client.config.prefix}market <ticker>`;
    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]);
      let stock: stockInfo.Stock;
      try {
        stock = await stockInfo.getSingleStockInfo(args[0]);
      } catch (err) {
        return this.error(message.channel, `Unable to fetch information for that ticker. | ${err}`);
      }

      const embed = new RichEmbed();
      embed.setTitle(stock.longName ?? stock.symbol);
      let type: string;
      switch (stock.quoteType) {
        case 'EQUITY':
          type = 'Common/Preferred Stock';
          break;
        case 'ETF':
          type = 'Exchange Traded Fund (ETF)';
          break;
        case 'MUTUALFUND':
          type = 'Mutual Fund';
          break;
        default:
          type = 'N/A or Unknown';
          break;
      }
      embed.addField('Type', type, true);
      embed.addField('Market Cap', `${stock.marketCap ? this.client.util.hrn(stock.marketCap, undefined, undefined) : 'N/A'}`, true);
      embed.addField('Day Quote Price', stock.regularMarketPrice ? `$${Number(stock.regularMarketPrice).toFixed(2)}` : 'N/A', true);
      embed.addField('Day G/L', stock.regularMarketChange ? `$${Number(stock.regularMarketChange.toFixed(2))}` : 'N/A', true);
      embed.addField('Day Range', stock.regularMarketDayRange ?? 'N/A', true);
      embed.addField('Bid/Ask', `Bid: $${stock.bid?.toFixed(2) ?? 'N/A'} | Ask: $${stock.ask?.toFixed(2) ?? 'N/A'}`, true);
      embed.addField('Forward P/E (Price/Earnings)', `${stock.forwardPE?.toFixed(2) ?? 'N/A'}`, true);
      embed.addField('Forward EPS (Earnings Per Share)', `${stock.epsForward?.toFixed(2) ?? 'N/A'}`, true);
      embed.addField('Exchange', `${stock.fullExchangeName?.toUpperCase() ?? 'N/A'}`, true);
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      embed.setTimestamp();
      return message.channel.createMessage({ embed });
    } catch (err) {
      return this.client.util.handleError(err, message, this, false);
    }
  }
}
