import { Component, OnInit, OnDestroy } from '@angular/core';
import { ApiService } from '../../services/login-api';
import { NbWindowService, NbDialogService } from '@nebular/theme';
import { FrontcraftCreateRaidsComponent } from './createraid.compontent';
import { Router, NavigationStart } from '@angular/router';

@Component({
  selector: 'raids',
  templateUrl: 'raids.component.html',
  styleUrls: ['raids.component.scss'],
})
export class FrontcraftRaidsComponent implements OnInit, OnDestroy{


  manageRaid
  raids = []
  oldraids = []
  pageSize = 10;
  uuid

  constructor(
    private api: ApiService,
    private router: Router,
    private dialogService: NbDialogService
  ) {
    this.manageRaid = this.api.get('manageRaid')
    router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        this.ngOnDestroy()
      }
    })
  }

  ngOnDestroy = () => {
    console.log("boom");

    if(this.uuid)
      this.api.get('PubSub').unsubscribe(this.uuid)
  }

  async ngOnInit() {
    const res = await this.api.get('PubSub').subscribe("raids", () => {
      this.refresh()
    })
    this.uuid = res.uuid
    this.refresh()
  }

  refresh() {
    this.api.get('RaidManager').getRaids().then(raids => {
      this.raids = raids
    })

    const raidManager = this.api.get('RaidManager')
    raidManager.getPastRaids(10).then(raiddata => {
      this.oldraids = raiddata
    })
  }

  create(){
    this.dialogService.open(FrontcraftCreateRaidsComponent, { 
      closeOnBackdropClick: true,
      closeOnEsc: true,
      context: {
        templates: this.oldraids
      } 
    })

  }
}
