import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router, NavigationStart } from '@angular/router';
import { ApiService as ApiService } from '../../services/login-api';
import { RaidData, Raid, Signup, Character, Spec, Item, SRToken } from '../../../../../../backend/Types/Types';
import { NbWindowService, NbToastrService, NbDialogService } from '@nebular/theme';
import { FrontcraftCharacerpickerComponent } from './characterpicker.component';
import { getClassColor, SpecT } from '../../../../../../backend/Types/PlayerSpecs';
import { FrontcraftBuyTokenComponent } from '../shop/buytoken.component';
import { allItems } from '../../../../../../backend/Types/Items';

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

    canSignup = false
    isSignedup = false
    islate = false
    isTier = false
    manageRaid
    mySignup: (Signup & Character & Spec)

    raid: RaidData = <any>{
      participants:{
          Druid: [],
          Hunter: [],
          Mage: [],
          Paladin: [],
          Priest: [],
          Rogue: [],
          Shaman: [],
          Warlock: [],
          Warrior: [],
      },
      tanks: [],
      healers: [],
      tokens:{},
      tier: 'MC'
    }
    tokens = {}
    displayedtokens = {}
    search = ""
    uuid

    constructor(
      private api: ApiService,
      private route: ActivatedRoute,
      private router: Router,
      private dialogService : NbDialogService,
      private toast: NbToastrService
    ){
      window['r'] = this
      router.events.subscribe(event => {
        if (event instanceof NavigationStart) {
          this.ngOnDestroy()
        }
      })
    }

    ngOnDestroy = () => {
      if(this.uuid)
        this.api.get('PubSub').unsubscribe(this.uuid)
    }

    async ngOnInit(){
      
      this.manageRaid = this.api.get('manageRaid')
      
      const signupFeature = this.api.get('signup')
      if(signupFeature){
        this.canSignup = true
      }
      await this.refresh()

      const res = await this.api.get('PubSub').subscribe(""+this.raid.id!, (data: RaidData) => {
        this.display(data)
      })
      this.uuid = res.uuid
    }

 

    itemSelect = async(item) => {
      this.dialogService.open(FrontcraftBuyTokenComponent, {
        context: {
          item: item,
          signup: this.mySignup,
          tier: this.raid.tier,
          characterName: this.mySignup.charactername
        }
      })
    }

    signup = async () => {
      const signupFeature = this.api.get('signup')
      if(!signupFeature) return

      this.dialogService.open(FrontcraftCharacerpickerComponent, { 
        closeOnBackdropClick: true,
        closeOnEsc: true,
        context: {
          raid: this.raid,
        } 
      })
    }

    async archiveRaid(raid:Raid){
      await this.manageRaid!.archiveRaid(raid)
      this.toast.show('Raid archived', 'Success', { status: 'success' })
      this.router.navigateByUrl('/frontcraft/archive/'+raid.id)
    }

    async startRaid(raid:Raid){
      await this.manageRaid!.startRaid(raid)
      this.toast.show('Raid started', 'Success', { status: 'success' })
      this.router.navigateByUrl('/frontcraft/archive/'+raid.id)
    }

    unsign = async () => {
      const signupFeature = this.api.get('signup')
      if(!signupFeature) return

      await signupFeature.unsign(this.api.getAuth().token.value, {
        ...this.mySignup,
        id: this.mySignup.characterid, 
      }, this.raid)
      this.toast.show('Success', 'Unsigned', { status: 'success' })
    }

    setLate = async (value:boolean) => {
      const auth = this.api.getAuth()
      const signup = this.api.get('signup')
      if(!signup) return

      await signup.sign(auth.token.value, {
        ...this.mySignup,
        id: this.mySignup.characterid,
      }, this.raid, value)
      this.toast.show('Signup', 'Success', { status: 'success' })
    }

    adminUnsign = async() => {
      const manage =  this.api.get('manageRaid')
      if(!manage) return
      await manage.adminUnsign({
        ...this.mySignup,
        id: this.mySignup.characterid, 
      }, this.raid)
    }

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

      const raidManager = this.api.get('RaidManager')
      const raiddata = await raidManager.getRaidData(<any>{
        id: param
      })
      this.display(raiddata)
      
    }

    display =  async (raiddata:RaidData)  => {
      this.isTier = allItems[raiddata.tier] != null

      this.raid = raiddata
      this.tokens = raiddata.tokens;

      [...raiddata.tanks, ...raiddata.healers, ...Object.values(raiddata.participants).flat()].forEach(p => {
        p['color'] = getClassColor(p.class)
      })

      const user = this.api.getCurrentUser()
      const matchingSignup = Object.values(raiddata.participants).flat().find(char => user && char.userid === user.id!)
      if(matchingSignup){       
        this.isSignedup = true
        this.mySignup = matchingSignup
        this.mySignup['status'] = matchingSignup['benched']?'Bench':matchingSignup['late']?'Late':'Attending'
      }else{
        this.isSignedup = false
        this.mySignup = null
      }
      this.changeSearch()
    }

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

    setBench(signup:Signup){
      this.manageRaid.setBenched({
        characterid: signup.characterid,
        raidid: signup.raidid,
        late: false,
        benched: !signup.benched
      }).then(_ => this.refresh())
    }
}