import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RaidData } from '../../../../../../backend/Types/Types';
import { getClassColor } from '../../../../../../backend/Types/PlayerSpecs';
import { IApiService } from '../../services/ApiService/ApiService';
import { LoggerService } from '../../services/LoggerService/logger.service';

@Component({
  selector: 'archive',
  templateUrl: './raid.component.html',
})
export class FrontcraftArchiveComponent implements OnInit{

    manageRaid = false
    canSignup = false
    isSignedup = false
    canManage = false
    isTier = false
    mySignup

    raid: RaidData = <any>{
      participants:{
          Druid: [],
          Hunter: [],
          Mage: [],
          Paladin: [],
          Priest: [],
          Rogue: [],
          Shaman: [],
          Warlock: [],
          Warrior: [],
      },
      tokens:{},
      tanks:[],
      healers: []
    }
    tokens: {[key in string]:any[]} = {}
    displayedtokens = {}
    search = ""
    
    constructor(
      private api: IApiService,
      private route: ActivatedRoute,
      private router: Router,
      private logger: LoggerService
    ){
    }

    async ngOnInit(){
      this.refresh()
    }

    refresh = async () => {
      const param = this.route.snapshot.paramMap.get('id');

      const raidManager = this.api.get('RaidManager')
      try{
        const raiddata = await raidManager.getArchiveRaid(parseInt(param))
        if(!raiddata) throw new Error('Unable to get raid')

        this.raid = raiddata
        this.isTier = raiddata.tier != null
        this.tokens = raiddata.tokens
        this.displayedtokens = this.tokens;
  
        [
          ...raiddata.tanks, 
          ...raiddata.healers, 
          ...Object.values<any>(raiddata.participants).flat()
        ].forEach(p => {
          p['color'] = getClassColor(p.class)
          if(!p.timestamp)
            p.before = 5.184e+8 //7 days
          else
            p['before'] = Number.parseInt(this.raid.start) - Date.parse(p.timestamp)
        })
  
        this.changeSearch()
      }catch(e){
        this.router.navigate(["/"])
      }
    }

    changeSearch(){
      if(!this.search || this.search == ""){
        this.displayedtokens = this.tokens
      }else{
        this.displayedtokens = {}
        Object.entries(this.tokens).forEach((e) => {
          const filteredTokens = e[1].filter(item => {
            return item.itemname.toLocaleLowerCase().includes(this.search.toLocaleLowerCase())
          })
          if(filteredTokens.length > 0)
            this.displayedtokens[e[0]] = filteredTokens 
        })
      }
    }
}