import { Component, HostListener, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { getColorOrder2 } from 'src/app/lib/filler/common/color-order';
import SVGGenerator from 'src/app/lib/filler/common/svg-generator3';
import Utils from 'src/app/lib/filler/common/utils';
import ImageLayer from 'src/app/lib/filler/core/image-layer';
import { EditorDirective } from 'src/app/lib/filler/editor.directive';
import { ArtService } from './art.service';
import { ArtBin, EditorInputData } from './play.component';


const TAG = 'Svg3Component';


@Component({
  selector: 'app-svg3',
  template: `

    <canvas appEditor ></canvas>
    <div *ngIf="!generator?.done" class="progress d-flex flex-column justify-content-center align-items-center"  >
      <span>
        <ng-container i18n>进度</ng-container>:{{generator?.progress | percent}}
      </span>
    </div>

  `,
  styles: [
    `
    :host{
      display:block;
      width:100vw;
      height:100vh;
    }

    canvas{
      width:100vw;
      height:100vh;
    }

    .progress{
      position:absolute; 
      text-align:center;
      font-size:20px;
      left: 50%;
      top:50%;
      transform: translate(-50%, -50%);
      width:200px;
      height:200px;
      background-color:transparent;
    }
    `
  ]
})
export class Svg3Component implements OnInit {

  @HostListener('window:keydown', ['$event'])
  keyEvent(event: KeyboardEvent) {

    let key = event.key.toLocaleLowerCase();
    let isCtrl = event.ctrlKey;
    let isMeta = event.metaKey;
    let isCtrlOrMeta = isCtrl || isMeta;

    console.log(key, isCtrl, isMeta);


    if ('1' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[0], false);
    } else if ('2' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[1], false);
    } else if ('3' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[2], false);
    } else if ('4' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[3], false);
    } else if ('5' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[4], false);
    } else if ('6' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[5], false);
    } else if ('7' == key) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayers[6], false);
    }
  }


  id : string;
  art : any;
  dataInput :EditorInputData;
  imageLayers: ImageLayer[] = [];
  curveSvg1File : string;
  curveSvg2File : string;
  lineSvg1File: string;
  lineSvg2File: string;
  contourFile: string;
  @ViewChild(EditorDirective) editoRef : EditorDirective;

  generator : SVGGenerator;

  constructor(
    private artService : ArtService,
    private activatedRoute : ActivatedRoute,
    private message : NzMessageService,
  ) { 

    
  }

  async onRemoteData() {
    if (!this.art) return;

    console.log(TAG, 'onRemoteData', this.art);

    let input = {};
    //console.log(Object.values(this.doc));
    let artBins: ArtBin[] = (Object.values(this.art).filter((prop: any) => prop && prop.type)) as ArtBin[];
    for (var i = 0; i < artBins.length; i++) {
      let bin = artBins[i];
      if (bin.mime.startsWith('image')) {
        input[bin.type] = await Utils.base64ToImage(bin.data_base64, bin.mime)
      } else if (bin.mime.startsWith('application/json')) {
        input[bin.type] = bin.data_json;
      }
    }

    this.dataInput = input as EditorInputData;

    let colorOrder = getColorOrder2(this.dataInput.colorMap, this.dataInput.centers, this.dataInput.colorOrder, this.dataInput.orderAuto);

    let generator  = new SVGGenerator(this.dataInput.map, this.dataInput.page, this.dataInput.org, this.dataInput.colorMap, this.dataInput.centers, colorOrder);
    this.generator = generator;

    console.time("generate svg3");
    let blobs = await generator.process();
    console.timeEnd("generate svg3");

    let images = {};
    for (let key of Object.keys(blobs)) {
      images[key] = await Utils.blobToImage(blobs[key]);
      this.imageLayers.push(new ImageLayer(images[key]));
    }
    this.imageLayers.push(new ImageLayer(this.dataInput.map));

    this.download(blobs['svg1'], this.curveSvg1File);
    this.download(blobs['svg2'], this.curveSvg2File);
    this.download(blobs['svg3'], this.lineSvg1File);
    this.download(blobs['svg4'], this.lineSvg2File);
    this.download(blobs['contour'], this.contourFile);

    this.editoRef?.editor.setBackgroundLayer(this.imageLayers[0], true);

    console.log(TAG, 'onRemoteData@dataInput', this.dataInput);
  }


  download(blob : Blob, filename : string) {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
  }

  ngOnInit(): void {

    this.id = this.activatedRoute.snapshot.params['id'];
    this.artService.getAll(this.id).subscribe({
      next : resp => {
        this.art = resp;
        this.curveSvg1File = this.art.name + '-curve1' + '.svg';
        this.curveSvg2File = this.art.name + '-curve2' + '.svg';
        this.lineSvg1File = this.art.name + '-line1' + '.svg';
        this.lineSvg2File = this.art.name + '-line2' + '.svg';
        this.contourFile = this.art.name + '-contour' + '.png';
        this.onRemoteData()
        .catch(console.error)
      },
      error : err => this.message.error(err.error?.message || err.message),
    })

  }

}
