/* eslint-disable prefer-destructuring */
import { Activity, Member, Message } from 'eris';
import { Client, Command, RichEmbed } from '../class';

enum ActivityType {
  PLAYING,
  STREAMING,
  LISTENING,
  WATCHING,
  CUSTOM_STATUS
}

export default class Game extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'game';
    this.description = 'Displays information about the member\'s game.';
    this.usage = 'game [member]';
    this.permissions = 0;
    this.aliases = ['activity'];
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      let member: Member;
      if (!args[0]) member = message.member;
      else {
        member = this.client.util.resolveMember(args.join(' '), this.mainGuild);
        if (!member) {
          return this.error(message.channel, 'Member not found.');
        }
      }
      if (!member.activities || member.activities.length <= 0) return this.error(message.channel, 'Cannot find a game for this member.');
      const embed = new RichEmbed();
      let mainStatus: Activity;
      if (member.activities[0]?.type === ActivityType.CUSTOM_STATUS) {
        mainStatus = member.activities[1];
        embed.setDescription(`*${member.activities[0].state}*`);
      } else {
        mainStatus = member.activities[0];
      }
      embed.setAuthor(member.user.username, member.user.avatarURL);
      if (mainStatus?.type === ActivityType.LISTENING) {
        embed.setTitle('Spotify');
        embed.setColor('#1ed760');
        embed.addField('Song', mainStatus.details, true);
        embed.addField('Artist', mainStatus.state, true);
        embed.addField('Album', mainStatus.assets.large_text);
        embed.addField('Start', `${new Date(mainStatus.timestamps.start).toLocaleTimeString('en-us')} ET`, true);
        embed.addField('End', `${new Date(mainStatus.timestamps.end).toLocaleTimeString('en-us')} ET`, true);
        embed.setThumbnail(`https://i.scdn.co/image/${mainStatus.assets.large_image.split(':')[1]}`);
        embed.setFooter(`Listening to Spotify | ${this.client.user.username}`, 'https://media.discordapp.net/attachments/358674161566220288/496894273304920064/2000px-Spotify_logo_without_text.png');
        embed.setTimestamp();
      } else {
        return this.error(message.channel, 'Only Spotify games are supported at this time.');
      }
      return message.channel.createMessage({ embed });
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
