import { Subscription } from 'rxjs';
import { AttacksFeatureState, AttacksState } from './../store/attacks.redurecs';
import { Store } from '@ngrx/store';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { RequestAttacksListAction } from '../store/attacks.actions';
import { Attack } from '../model/attack.model';

@Component({
  selector: 'app-attack-detail',
  templateUrl: './attack-detail.component.html',
  styleUrls: ['./attack-detail.component.scss']
})
export class AttackDetailComponent implements OnInit, OnDestroy {

  private storeSubscription: Subscription;
  public attack: Attack;
  private attacks: Attack[];

  constructor(private route: ActivatedRoute, private router: Router, private store: Store<AttacksFeatureState>) {
    let id = this.route.snapshot.params['id'];
    if (!id)
      this.router.navigate(['/database']);
    this.storeSubscription = this.store.select('attacks').subscribe(
      (state: AttacksState) => {
        if (state.attacks === null)
          store.dispatch(new RequestAttacksListAction());
        else {
          this.attacks = state.attacks;
          let attack = state.attacks.find((attack: Attack) => attack.id === +id);
          if (!attack)
            this.router.navigate(['/database']);
          this.attack = attack;
        }
      }
    );
  }

  ngOnInit() {
  }

  ngOnDestroy(){
    this.storeSubscription.unsubscribe();
  }

  private getRelatedAttackDescById(id: number): string{
    let attack: Attack = this.attacks.find((attack: Attack) => { return attack.id === id });
    return attack ? attack.city+", "+attack.country+", "+attack.date : '';
  }

}
