import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NbDialogService } from '@nebular/theme';
import { Subject, Observable } from 'rxjs';
import { first, takeUntil } from 'rxjs/operators';
import { MD2Service } from '../../../services/MD2/md2.service';
import { MsgBoxService } from '../../../services/msg-box.service';
import { StateService } from '../../../services/state.service';
import { ADIcon } from '../../../ui/alert-dlg/alert-dlg.model';
import { MD2Icon, MobDlgType, MobInfo } from '../massive-darkness2.model';
import { MD2ComponentBase } from '../MD2Base';
import { SpawnMobDlgComponent } from '../mobs/spawn-mob-dlg/spawn-mob-dlg.component';

@Component({
  selector: 'md2-boss-fight',
  templateUrl: './boss-fight.component.html',
  styleUrls: ['./boss-fight.component.scss']
})
export class BossFightComponent extends MD2ComponentBase {
  MobDlgType = MobDlgType;
  MD2Icon = MD2Icon;
  public get boss() {
    return this.md2Service.info.boss;
  }


  constructor(
    private msgBoxService: MsgBoxService,
    private dlgService: NbDialogService,
    public md2Service: MD2Service,
    protected stateService: StateService,
    protected route: ActivatedRoute,
    protected cdRef: ChangeDetectorRef,
  ) {
    super(md2Service, stateService, route, cdRef);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.md2Service.heroAttackingSubject.pipe(takeUntil(this.destroy$)).subscribe(result => {
      if (this.md2Service.info.isBossFight) {
        this.attack(this.boss.info);
      }
    });
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
  activate() {
    this.boss.activating();
  }
  WIN() {
    this.msgBoxService.show('Win', { text: 'You Win the Boss Fight', icon: ADIcon.INFO });
    this.md2Service.info.isBossFight = false;
    this.md2Service.info.boss = undefined;
    this.md2Service.heros.forEach(h => h.uiBossFight = false);
    this.md2Service.broadcastGameInfo();
  }
  attack(mob: MobInfo) {

    this.dlgService.open(SpawnMobDlgComponent, { context: { title: `Attack ${this.boss.name}`, mode: MobDlgType.BeenAttacked, mob: mob } })
      .onClose.pipe(first()).subscribe(mobResult => {
        if (mobResult) {
          let attackDamage = mobResult.uiWounds;
          if (attackDamage) {
            this.boss.info.unitRemainHp -= attackDamage;
            if (this.boss.info.unitRemainHp <= 0) {
              this.WIN();
            }
            this.cdRef.detectChanges();
          }
        }

      });

  }
}
