import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  OnChanges,
  OnInit,
  ViewChild,
} from "@angular/core";
import { MatDialog } from "@angular/material/dialog";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
//import * as SimpleMarkdown from 'simple-markdown';

import hljs from "node_modules/highlight.js/lib/common";
import { OutboundLinkDialogComponent } from "src/app/shared/dialogs/outbound-link-dialog/outbound-link-dialog.component";
import { RouterHandler } from "src/app/shared/services/router-handler.service";
import { EnvironmentService } from "src/environments/environment.service";
import { AttachedFileUrl } from "./markdown-file-preview/markdown-file-preview.component";
declare let SimpleMarkdown;

@Component({
  selector: "app-markdown-view",
  templateUrl: "./markdown-view.component.html",
  styleUrls: ["./markdown-view.component.scss"],
})
export class MarkdownViewComponent implements OnInit, AfterViewInit {
  @Input() set html(value: string) {
    this.refreshContent(value);
  }

  @ViewChild("output", { read: ElementRef }) output: any;

  public htmlView;
  public attachedFileUrl: AttachedFileUrl[] = [];

  constructor(
    private dialog: MatDialog,
    private environmentService: EnvironmentService,
    private routerHandler: RouterHandler
  ) {}

  ngOnInit(): void {}

  ngAfterViewInit(): void {
    this.output.nativeElement.querySelectorAll("pre code").forEach((el) => {
      hljs.highlightElement(el);
    });
    this.output.nativeElement.querySelectorAll("a").forEach((el) => {
      if (el.href.startsWith(this.environmentService.url_landing)) {
        el.setAttribute("target", "_blank");
      } else if (el.href.startsWith(this.environmentService.site_base)) {
        let [base, url] = el.href.split(
          this.environmentService.site_base + "/"
        );

        if (url) {
          let response = this.routerHandler.processUrl(url);

          if (this.routerHandler.isUrlOnPage(url, "room/?/drive")) {
            let file = response.routerResponse.fragment["file"]; // name of the file (as path)
            let roomId = response.routerResponse.params["id"];
            let path = response.routerResponse.fragment["path"]; // path before the file
            if (file && roomId) {
              this.attachedFileUrl.push({
                file,
                roomId,
                path,
              });
            }
          }

          el.addEventListener("click", (e: MouseEvent) => {
            e.preventDefault();
            this.routerHandler.navigate([response.routerResponse.url], {
              fragment: response.routerResponse.rawFragment,
            });
          });
        }
      } else {
        el.setAttribute("target", "_blank");
        el.addEventListener("click", this.askBeforeNavigate);
      }
    });
  }

  private askBeforeNavigate = (e: MouseEvent) => {
    e.preventDefault();
    var anchorElement = <HTMLAnchorElement>e.target;
    var dialog = this.dialog.open(OutboundLinkDialogComponent, {
      data: { href: anchorElement.href, host: anchorElement.origin },
    });
    dialog.afterClosed().subscribe((res) => {
      if (res) {
        anchorElement.removeEventListener("click", this.askBeforeNavigate);
      }
    });
  };

  private refreshContent(content) {
    let parser = SimpleMarkdown.defaultBlockParse;
    let viewer = SimpleMarkdown.defaultHtmlOutput;

    let syntaxTree = parser(content);

    this.htmlView = viewer(syntaxTree);
  }
}
