import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FileService } from '../../services/file.service';
import { MsgBoxService } from '../../services/msg-box.service';
import { ArrayUtils } from '../../utilities/array-utils';
import { ObjectUtils } from '../../utilities/object-utils';
import { first, map, take, takeUntil } from 'rxjs/operators';
import { TreasureType, DrawingBag, DrawingItem, HeroClass, MD2HeroInfo, RoundPhase, MobInfo, MobDlgType, MD2Icon } from './massive-darkness2.model';
import { MD2Service } from '../../services/MD2/md2.service';
import { GameRoomService } from '../../services/game-room.service';
import { MD2Base } from './MD2Base';
import { StateService } from '../../services/state.service';
import { ActivatedRoute } from '@angular/router';
import { QRCodeService } from '../../services/qrcode.service';
import { StringUtils } from '../../utilities/string-utils';
import { SpawnMobDlgComponent } from './mobs/spawn-mob-dlg/spawn-mob-dlg.component';
import { BossMicheal } from './massive-darkness2.model.boss';
import { MD2InitService } from '../../services/MD2/md2-init.service';
import { NumberUtils } from '../../utilities/number-utils';

@Component({
  selector: 'ngx-massive-darkness2',
  templateUrl: './massive-darkness2.component.html',
  styleUrls: ['./massive-darkness2.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MassiveDarkness2Component extends MD2Base implements OnInit {
  MD2Icon = MD2Icon;
  HeroClass = HeroClass;
  constructor(
    private fileService: FileService,
    private initService: MD2InitService,
    private msgBoxService: MsgBoxService,
    private qrCodeService: QRCodeService,
    public gameRoomService: GameRoomService,
    public md2Service: MD2Service,
    protected stateService: StateService,
    protected route: ActivatedRoute,
    protected cdRef: ChangeDetectorRef,
  ) {
    super(md2Service, stateService, route, cdRef);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.md2Service.enemyPhaseSubject.pipe(takeUntil(this.destroy$)).subscribe(result => {
      this.showEnemyPhaseAction(0);
    });
    this.initService.initMobDecks();
    this.initService.initTreasureBag();
  }
  override signalRInitialized() {

  }
  adjustHeroValue(hero: MD2HeroInfo, value: string) {
    this.msgBoxService.showInputbox(`Adjust ${value} for ${hero.playerInfo.name}`, `Enter the new value for ${value}`, {
      inputType: 'number',
      inputValue: hero[value].toString()
    }).pipe(first()).subscribe(result => {
      if (result) {
        hero[value] = Number.parseInt(result);
        this.md2Service.broadcastHeroInfoToAll(hero, true);
        this.detectChanges();
      }
    });
  }
  activatingHero(hero: MD2HeroInfo) {
    if (hero.remainActions > 0) {
      this.msgBoxService.show('Activating', { text: `Are you sure you want to activate ${hero.playerInfo.name}?` }).pipe(first()).subscribe(result => {
        if (result) {
          this.md2Service.heros.forEach(h => h.uiActivating = false);
          hero.uiActivating = true;
          this.md2Service.broadcastAllHeroInfoToAll();
          this.detectChanges();
        }
      });
    }

  }
  showQrCode() {
    if (this.md2Service.initialized == false) {
      this.gameRoomService.createGameRoom('MD2');
      this.md2Service.initialized = true;
    }
    let initUrl = `${window.location.origin}/games/MD2_Hero/${this.gameRoomService.gameRoomId}`;
    this.msgBoxService.show("Scan To Join", { text: `<img src='${this.qrCodeService.QRCodeUrl(initUrl, 5)}'><br><a href='${initUrl}' target='_blank'>Link</a>` });
  }
  refreshUI() {
    console.log('Dashboard RefreshUI');

  }
  heroClassName(heroInfo: MD2HeroInfo) {
    return HeroClass[heroInfo.class];
  }

  showEnemyPhaseAction(index: number) {
    let mob = this.md2Service.enemyPhaseMobs[index];
    let enemyInfo = `<img src="${mob.imageUrl}" class='g-height-70vh'><br>`;
    let extraRule = '';

    // switch (Math.random() * 3) {

    //   case 1:

    //     break;
    //   case 2:

    //     break;
    //   case 3:

    //     break;

    //     case 0:
    //   default:
    //     break;
    // }

    this.msgBoxService.dlgService.open(SpawnMobDlgComponent, {
      context: {
        title: `Enemy Phase(${(index + 1)}/${this.md2Service.enemyPhaseMobs.length})`,
        mode: MobDlgType.Activating,
        mob: mob
      }
    })
      .onClose.pipe(first()).subscribe(result => {
        index++;
        if (index < this.md2Service.enemyPhaseMobs.length) {
          this.showEnemyPhaseAction(index);
        } else {
          this.md2Service.runNextPhase();
        }
      });
    // return this.msgBoxService.show(`Enemy Phase(${(this.enemyPhaseMobs.indexOf(mob) + 1)}/${this.enemyPhaseMobs.length})`, {
    //   text: enemyInfo,
    //   confirmButtonText: 'Next', buttons: ADButtons.OK
    // }).pipe(first()).subscribe(result => {
    //   if ((this.enemyPhaseMobs.indexOf(mob) + 1) < this.enemyPhaseMobs.length) {
    //     this.showEnemyPhaseAction(this.enemyPhaseMobs[this.enemyPhaseMobs.indexOf(mob) + 1]);
    //   }
    // });
  }
  public get roundPhase(): string {
    switch (this.md2Service.info.roundPhase) {
      case RoundPhase.HeroPhase:
        return StringUtils.getHtmlBadge("Hero Action Phase", "primary")
      case RoundPhase.EnemyPhase:
        return StringUtils.getHtmlBadge("Enemy Action Phase", "danger")
      case RoundPhase.LevelUpPhase:
        return StringUtils.getHtmlBadge("Level Up Phase", "success")
      case RoundPhase.DarknessPhase:
        return StringUtils.getHtmlBadge("Darkness Phase", "dark")
      default: break;
    }
  }

  public get anyHeroRemainAction(): boolean {
    return this.md2Service.heros.some(h => h.remainActions > 0);
  }

  heroAction(hero: MD2HeroInfo, action: string) {

  }
  enterBossFight() {
    this.md2Service.enterBossFight();

  }
  accessHealFountain() {
    this.md2Service.drawingHealFountain();
  }
  broadcastHeros() {
    this.md2Service.heros.forEach(hero => {
      hero.uiShowAttackBtn = this.md2Service.mobs.length > 0 || this.md2Service.roamingMonsters.length > 0 || this.md2Service.info.isBossFight;
    });
    this.md2Service.broadcastAllHeroInfoToAll();
  }
  removeHero(hero) {
    this.msgBoxService.showConfirmDeleteBox().pipe(first()).subscribe(result => {
      if (result) {
        this.md2Service.info.heros.splice(this.md2Service.info.heros.indexOf(hero));
        this.cdRef.detectChanges();
      }
    });
  }


  public get round(): string {
    if (this.md2Service.info.isBossFight) {
      return `Boss Fight ${NumberUtils.Ordinal(this.md2Service.info.boss.rounds)} Round`;
    } else {
      return NumberUtils.Ordinal(this.md2Service.info.round) + ' Round';
    }
  }

}