import { Component, 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-generator';
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 = 'SvgComponent';


@Component({
  selector: 'app-svg',
  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 SvgComponent implements OnInit {
  id : string;
  art : any;
  dataInput :EditorInputData;
  imageLayer : ImageLayer;
  filename : 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 svg");
    let svgBlob = await generator.process();
    console.timeEnd("generate svg");
    let svgImage = await Utils.blobToImage(svgBlob);

    // this.upload(this.id, svgBlob);

    this.download(svgBlob, this.filename);

    // this.imageLayer = new ImageLayer(svgImage, this.dataInput.raw);
    this.imageLayer = new ImageLayer(svgImage);
    this.editoRef?.editor.setBackgroundLayer(this.imageLayer, true);

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


  upload(artId: string, svgv1 : Blob) {
    let form = new FormData();
    form.set('svgv1', svgv1);
    form.set('ignoreStatus', '1');
    this.artService.update(form, artId).subscribe({
      next : resp => {
        this.message.success($localize`更新成功！`);
      },
      error : err => {
        this.message.error(err.error?.message || err.message);
      }
    })
  }


  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 {
    if(this.imageLayer) {
      this.editoRef?.editor.setBackgroundLayer(this.imageLayer, true);
    }


    this.id = this.activatedRoute.snapshot.params['id'];
    this.artService.getAll(this.id).subscribe({
      next : resp => {
        this.art = resp;
        this.filename = this.art.tags.join('-') + '.svg';
        this.onRemoteData()
        .catch(console.error)
      },
      error : err => this.message.error(err.error?.message || err.message),
    })

  }

}
