/* eslint-disable no-await-in-loop */
/* eslint-disable no-continue */
/* eslint-disable default-case */
import { median, mode, mean } from 'mathjs';
import { User } from 'eris';
import { Client, CmdContext, Command, RichEmbed } from '../class';
import { getTotalMessageCount } from '../functions/calculateReport';

export default class Score_Hist extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'hist';
    this.description = 'Pulls a Community Report history for a user.';
    this.usage = `${this.client.config.prefix}score hist <member>`;
    this.permissions = 0;
    this.guildOnly = false;
    this.enabled = true;
  }

  public async run(ctx: CmdContext) {
    let user: User;
    if (!this.checkCustomPermissions(ctx.message.member, 4)) {
      user = ctx.message.author;
      await this.client.report.createInquiry(user.id, `${user.username}#${user.discriminator} VIA DISCORD - [HISTORICAL]`, 1);
    } else if (!ctx.args[0]) {
      user = ctx.message.author;
      await this.client.report.createInquiry(user.id, `${user.username}#${user.discriminator} VIA DISCORD - [HISTORICAL]`, 1);
    } else {
      user = this.client.util.resolveMember(ctx.args[0], this.mainGuild)?.user;
      if (!user) {
        const sc = await this.client.db.mongo.Score.findOne({ pin: [Number(ctx.args[0].split('-')[0]), Number(ctx.args[0].split('-')[1]), Number(ctx.args[0].split('-')[2])] });
        user = this.client.util.resolveMember(sc.userID, this.mainGuild)?.user;

        let name = '';
        // eslint-disable-next-line no-unreachable-loop
        for (const role of this.client.util.resolveMember(ctx.message.author.id, this.mainGuild).roles.map((r) => this.mainGuild.roles.get(r)).sort((a, b) => b.position - a.position)) {
          name = `Library of Code sp-us | ${role.name} - [HISTORICAL]`;
          break;
        }
        await this.client.report.createInquiry(user.id, name, 1);
      }
    }
    if (!user) return this.error(ctx.message.channel, 'Member not found.');
    const hists = await this.client.db.mongo.ScoreHistorical.find({ userID: user.id }).lean().exec();
    if (!hists) return this.error(ctx.message.channel, 'No history found.');
    if (hists.length < 1) return this.error(ctx.message.channel, 'No history found.');
    const totalArray: number[] = [];
    const activityArray: number[] = [];
    const moderationArray: number[] = [];
    const roleArray: number[] = [];
    const cloudServicesArray: number[] = [];
    const otherArray: number[] = [];
    const miscArray: number[] = [];

    for (const hist of hists) {
      totalArray.push(hist.report.total);
      activityArray.push(hist.report.activity);
      moderationArray.push(hist.report.moderation);
      roleArray.push(hist.report.roles);
      cloudServicesArray.push(hist.report.cloudServices);
      otherArray.push(hist.report.other);
      miscArray.push(hist.report.staff);
    }

    const stat = {
      totalMean: mean(totalArray),
      totalMode: mode(totalArray),
      totalMedian: median(totalArray),
      activityMean: mean(activityArray),
      rolesMean: mean(roleArray),
      moderationMean: mean(moderationArray),
      cloudServicesMean: mean(cloudServicesArray),
      otherMean: mean(otherArray),
      miscMean: mean(miscArray),
    };

    let totalMean = '0';
    let totalMedian = '0';
    let totalMode = '0';
    let activityMean = '0';
    let moderationMean = '0';
    let roleMean = '0';
    let cloudServicesMean = '0';
    let otherMean = '0';
    let miscMean = '0';

    if (stat.totalMean < 200) totalMean = '---';
    else if (stat.totalMean > 800) totalMean = '800';
    else totalMean = `${stat.totalMean}`;

    if (stat.totalMedian < 200) totalMedian = '---';
    else if (stat.totalMedian > 800) totalMedian = '800';
    else totalMedian = `${stat.totalMedian}`;

    if (stat.totalMode < 200) totalMode = '---';
    else if (stat.totalMode > 800) totalMode = '800';
    else totalMode = `${stat.totalMode}`;

    if (stat.activityMean < 10) activityMean = '---';
    else if (stat.activityMean > Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12))) activityMean = String(Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12)));
    else activityMean = `${stat.activityMean}`;

    if (stat.rolesMean <= 0) roleMean = '---';
    else if (stat.rolesMean > 54) roleMean = '54';
    else roleMean = `${stat.rolesMean}`;

    moderationMean = `${stat.moderationMean}`;

    if (stat.otherMean === 0) otherMean = '---';
    else otherMean = `${stat.otherMean}`;

    if (stat.miscMean <= 0) miscMean = '---';
    else miscMean = `${stat.miscMean}`;

    if (stat.cloudServicesMean === 0) cloudServicesMean = '---';
    else if (stat.cloudServicesMean > 10) cloudServicesMean = '10';
    else cloudServicesMean = `${stat.cloudServicesMean}`;



    const embed = new RichEmbed();
    embed.setTitle('Historical Community Report');
    embed.setAuthor(user.username, user.avatarURL);
    embed.setThumbnail(user.avatarURL);
    embed.setDescription(`__**Statistical Averages**__\n**CommScore™ Mean:** ${Number(totalMean).toFixed(2)} | **CommScore™ Mode:** ${Number(totalMode).toFixed(2)} | **CommScore™ Median:** ${Number(totalMedian).toFixed(2)}\n\n**Activity Mean:** ${Number(activityMean).toFixed(2)}\n**Roles Mean:** ${Number(roleMean).toFixed(2)}\n**Moderation Mean:** ${Number(moderationMean).toFixed(2)}\n**Cloud Services Mean:** ${Number(cloudServicesMean).toFixed(2)}\n**Other Mean:** ${Number(otherMean).toFixed(2)}\n**Misc Mean:** ${Number(miscMean).toFixed(2)}`);
    embed.setFooter(this.client.user.username, this.client.user.avatarURL);

    return ctx.uniCreateMessage({ embed });
  }
}
