import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FileService } from '../../../services/file.service';
import { MsgBoxService } from '../../../services/msg-box.service';
import { ADButtons } from '../../../ui/alert-dlg/alert-dlg.model';
import { DrawingBag, DrawingItem } from '../massive-darkness2.model';
import { first } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { MD2Service } from '../../../services/MD2/md2.service';
import { StateService } from '../../../services/state.service';
import { MD2Base, MD2ComponentBase } from '../MD2Base';
import { SignalRMessage } from '../../../services/signal-r.service';

@Component({
  selector: 'md2-door-events',
  templateUrl: './door-events.component.html',
  styleUrls: ['./door-events.component.scss']
})
export class DoorEventsComponent extends MD2ComponentBase implements OnInit {

  constructor(
    private msgBoxService: MsgBoxService,
    public md2Service: MD2Service,
    protected stateService: StateService,
    protected route: ActivatedRoute,
    protected cdRef: ChangeDetectorRef,
  ) {
    super(md2Service, stateService, route, cdRef);
  }
  drawDoorEvents: DrawingItem[];
  treasureBag: DrawingBag<DrawingItem> = new DrawingBag<DrawingItem>();


  ngOnInit(): void {
    this.initDoorEvents();

    this.md2Service.signalRService.ReceivedSignalRMessageSubject.subscribe(result => this.handleSignalRCallback(result));
  }
  handleSignalRCallback(result: SignalRMessage): void {
    if (result.actionName == 'openDoor') {
      this.drawDoorCard();
    }
  }

  initDoorEvents() {
    this.drawDoorEvents = [];
    this.treasureBag = new DrawingBag<DrawingItem>();
    for (let i = 1; i <= 30; i++) {
      this.treasureBag.AddItem(new DrawingItem(i.toString(), '', this.imgUrl(`DoorEvents/DoorEvent-${i}.png`), 1));
    }
    this.cdRef.detectChanges();
  }
  drawDoorCard() {
    if (this.treasureBag.bagIsEmpty()) {
      this.treasureBag.RestoreRemoveItems();
    }
    let door = this.treasureBag.DrawAndRemove()[0];

    this.msgBoxService.show('', { text: `<img src="${door.imageUrl}" class="g-height-70vh g-max-width-80vw">`, buttons: ADButtons.YesNo, confirmButtonText: 'Keep It', cancelButtonText: 'Discard' })
      .pipe(first()).subscribe(result => {
        if (result) {
          door.name = this.md2Service.heroFullName(this.md2Service.currentActivateHero);
          this.drawDoorEvents.push(door);
        }
        this.cdRef.detectChanges();
      });
  }
  discard(door: DrawingItem) {
    this.drawDoorEvents.splice(this.drawDoorEvents.indexOf(door), 1);
    this.cdRef.detectChanges();
  }

}
