import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ToolConfigs } from '../../lib/filler/tool-config';
import { EditorDirective } from '../../lib/filler/editor.directive';
import { CheckerUploadComponent } from './checker-upload.component';
import { Location } from '@angular/common';
import MapEditLayer from '../../lib/filler/map-edit/map-edit-layer';
import { FileDomain, FileInfo } from './interfaces';
import FillArea from '../../lib/filler/common/fillarea';
import Rect from '../../lib/filler/core/rect';
import { ActivatedRoute } from '@angular/router';
import Utils from '../../lib/filler/common/utils';
import FloodFill2 from 'src/app/lib/filler/common/floodfill2';

@Component({
  selector: 'art-checker',
  templateUrl: './checker.component.html',
  styleUrls: ['./play.component.css']
})
export class CheckerComponent implements OnInit, OnDestroy {


  @ViewChild(EditorDirective)
  editorRef: EditorDirective;

  @ViewChild(CheckerUploadComponent)
  uploadRef: CheckerUploadComponent;

  mapEditLayer: MapEditLayer;

  layers: LayerInfo[] = [];
  scale: number = 1;

  isUpload: boolean = false;
  showAreaList: boolean = false;

  private id: string;


  constructor(
    public location: Location,
    private router: ActivatedRoute,
  ) {
    this.id = this.router.snapshot.paramMap.get('id') || '622c293a579039e772e3fd23';
  }

  ngOnInit() {
    if (this.id) {
      this.addLayer(true);
    }
  }


  get utils() { return Utils };


  get tools(): any[] {
    return this.editorRef.editor.getToolsStatus().map(ts => {
      let config = ToolConfigs[ts.key];
      if (config) Object.assign(ts, config);
      return ts;
    });
  }

  //get scale() { return this.editorRef.editor.getScale().x }
  //get currentLayer() { return this.editorRef.editor.getBackgroundLayer() }

  focusToArea(area: FillArea) {
    let rect = new Rect(area.left, area.top, area.right, area.bottom);
    this.editorRef.editor.focusToRect(rect);
    if (this.mapEditLayer) this.mapEditLayer.blinkByAreas([area]);
  }


  onOpenUpload() {
    this.isUpload = true;
  }

  onUpload(fis: FileInfo[]) {
    this.isUpload = false;
    let fisHash: FileInfoHash = fis.reduce((last: FileInfoHash, cur: FileInfo) => {
      last[cur.domain] = cur;
      return last;
    }, {});
    this.mapEditLayer = new MapEditLayer(fisHash['page'].image, fisHash['map'].image);
    this.editorRef.editor.setBackgroundLayer(this.mapEditLayer, true);
  }

  async addLayer(bestFit: boolean = false) {
    try {
      let url = `/napi/web/art/${this.id}/bin/raw`;
      let svg = await Utils.loadImageFromUrl(url);
      let blob = await Utils.convertToPngBlob(svg);
      let image = await Utils.blobToImage(blob);
      let ff = new FloodFill2(svg, null, this.scale);
      let map = await ff.toImage();
      let layer = new MapEditLayer(image, map);
      this.layers.push({
        layer: layer,
        name: this.scale + 'X',
      });
      await this.editorRef.editor.ready;
      this.mapEditLayer = layer;
      this.editorRef.editor.setBackgroundLayer(layer, bestFit);
      this.index = this.layers.length - 1;
      this.scale *= 2;
    } catch (err) {
      console.error(err);
    }
  }

  index = 0;

  switchLayer(index) {
    this.index = index;
    let layer = this.layers[index].layer;
    this.mapEditLayer = layer;
    this.editorRef.editor.setBackgroundLayer(layer);
  }


  ngOnDestroy() {
    this.layers.forEach(layer => layer.layer.destroy())
  }


}



interface LayerInfo {
  layer: MapEditLayer;
  name: string;
}


interface FileInfoHash {
  [FileDomain: string]: FileInfo;
}