import { Component, OnInit } from '@angular/core';
import { Item, Stats } from '../../../../../../backend/Types/Types';

import { NbToastrService } from '@nebular/theme';
import { IApiService } from '../../services/ApiService/ApiService';

@Component({
  selector: 'armory',
  templateUrl: './armory.component.html',
})
export class FrontcraftArmoryComponent implements OnInit {

  servers = servers
  submitted = false
  charactername = ""
  server = "Gandling"
  region = "EU"
  gear: Item[] = []

  constructor(
    private api: IApiService,
    private toastr: NbToastrService
  ) { }

  async submit() {
    const dataLink = "https://classic.warcraftlogs.com:443/v1/parses/character/" + this.charactername.toLowerCase().replace(/^\w/, c => c.toUpperCase()) + "/" + this.server + "/" + this.region + "?api_key=c698515ab4f592cdb848d80b3abe616c&metric=dps"

    fetch(dataLink).then(raw => raw.json().then(async (json: any[]) => {
      if (json.length < 1) return
      let data
      let min = -1

      for (let i = json.length - 1; i > 0; i--) {
        const start = Number.parseInt(json[i].startTime)
        if (start > min && json[i].gear[0].name != "Unknown Item") {
          min = start
          data = json[i]
        }
      }
      if (!data) {
        this.toastr.danger('Unknown character, or no warcraftlogs', "Error", {
          duration: 2000
        })
        return
      }

      const maybeItems: (Item | undefined)[] = await Promise.all(data.gear
        .filter(item => item.name != "Unknown Item")
        .map(async item => await this.api.get('ItemManager').getItem(item.name)))

      const geardata = maybeItems.filter(maybeItem => maybeItem != null)

      this.gear = geardata
      console.log(this.gear)
      console.log(this.gear.map(g => g.stats).reduce(sumStats))
    }))
  }

  async ngOnInit() {

  }
}

function sumStats(stat1: Stats, stat2: Stats): Stats {
  const ret = {} as any
  Object.keys(stat1).forEach(key => {
    ret[key] = stat1[key] + stat2[key]
  })
  return ret
}



const servers = [
  "Ashbringer"
  , "Bloodfang"
  , "Dreadmist"
  , "Firemaw"
  , "Flamelash"
  , "Gandling"
  , "Gehennas"
  , "Golemagg"
  , "Hydraxian Waterlords"
  , "Judgement"
  , "Mirage Rach"
  , "Mograine"
  , "Nethergarde"
  , "Noggenfogg"
  , "Pyrewood Village"
  , "Razorgore"
  , "Shazzrah"
  , "Skullflame"
  , "Stonespine"
  , "Ten Storms"
  , "Zandalar Tribe"
  , "Amnennar"
  , "Auberdine"
  , "Finkle"
  , "Sulfuron"
  , "Everlook"
  , "Lucifron"
  , "Razorfen"
  , "Patchwerk"
  , "Venoxis"
  , "Dragon’s Call"
  , "Lakeshire"
  , "Transcendence"
]