import { Component, ElementRef, Input, AfterViewInit, ViewChild } from '@angular/core';

import * as markmap from 'markmap-view';
import { Markmap, loadCSS, loadJS } from 'markmap-view';

import { Transformer, builtInPlugins } from 'markmap-lib';
// import "../../../node_modules/webfontloader/webfontloader.js";


@Component({
  selector: 'comp-markmap',
  templateUrl: './comp-markmap.component.html',
  styleUrls: ['./comp-markmap.component.scss'],
  standalone: true,
})
export class CompMarkmapComponent  implements AfterViewInit {

  @ViewChild("mapView") mapView:ElementRef | undefined
  @Input() markdown:string = ""
  @Input() height:string = "350px";
  constructor() { }

  ngAfterViewInit() {
    setTimeout(() => {
      
      this.loadMarkMap();
    }, 500);
  }

  loadMarkMap(){
    // 通过markmap-lib 解析markdown提取所需的结构和素材
    // With additional plugins
    const transformer = new Transformer([...builtInPlugins]);
    // 1. transform Markdown
    const { root, features } = transformer.transform(this.markdown);
    // 2. get assets
    // or get all possible assets that could be used later
    let assets = transformer.getAssets();

    assets.scripts?.forEach((item:any)=>{
      console.log(item)
      if(item.data?.src?.endsWith("webfontloader.js")){
        item.data.src = "assets/markmap/webfontloader.js"
      }
    })
    assets.styles?.forEach((item:any)=>{

      if(item.data?.src?.endsWith("katex.min.css")){
        item.data.src = "assets/markmap/katex.min.css"
      }
      if(item.data?.src?.endsWith("default.min.css")){
        item.data.src = "assets/markmap/default.min.css"
      }
    })
    console.log(assets)
    if(assets.styles){
     // 通过markmap-view 渲染svg效果图
      // 1. load assets
      if (assets.styles) loadCSS(assets.styles);
      if (assets.scripts) {
          loadJS(assets.scripts, {
            getMarkmap: () => markmap,
          }).then(()=>{
              // 向页面Dom渲染svg图
              // 2. create markmap
              // `options` is optional, i.e. `undefined` can be passed here
              setTimeout(() => {
                const svgEl = this.mapView?.nativeElement;
                console.log(svgEl,root)
                Markmap.create(svgEl, undefined, root); // -> returns a Markmap instance
              }, 1000);
          })
        }
    } 

     
    }

}
