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

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';
import { AppStorage } from 'src/app/shared/app-storage';
import {
  buildTokenTree,
  MarkdownToken,
  markdownTokens,
  MarkdownTokenTree,
  parseLineToTree,
  tokenizeMarkdownLines,
  TOKEN_TYPE,
} from '../slate-editor/markdown';
declare let SimpleMarkdown;

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

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

  public attachedFileUrl: AttachedFileUrl[] = [];

  isCompactDisplay = AppStorage.getItem('messageDisplay') === 'compact';

  public syntaxTree: MarkdownTokenTree | null = null;

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

  ngAfterViewInit(): void {
    //this.output.nativeElement.querySelectorAll('pre code').forEach((el) => {
    //  hljs.highlightElement(el);
    //});
  }

  private refreshContent(content) {
    this.syntaxTree = parseLineToTree(content);

    // collect urls
    let embedURLs = this.collectURL(this.syntaxTree);

    // collect attached file urls
    embedURLs.forEach((link) => {
      let [base, url] = link.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,
            });
          }
        }
      }
    });
  }

  /**
   * Collect all link type from the markdownTree
   * @param tree
   * @returns list of urls
   */
  private collectURL(tree: MarkdownTokenTree): string[] {
    let linkList = [];

    if (tree.token == TOKEN_TYPE.LINK) {
      linkList.push(tree.text);
    }

    if (tree.children) {
      tree.children.forEach((child) => {
        linkList = linkList.concat(this.collectURL(child));
      });
    }

    return linkList;
  }
}
