import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { UserGuideService } from '@app/core/services/user-guide/user-guide.service';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/internal/operators/takeUntil';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-user-guide-content',
  templateUrl: './user-guide-content.component.html',
  styleUrls: ['./user-guide-content.component.scss']
})
export class UserGuideContentComponent extends BaseComponent implements OnInit, AfterViewChecked {


	guideHTML: any;
	private scrollEvent: EventListener;

  constructor(
	  private userGuideService: UserGuideService,
	  private sanitizer: DomSanitizer
  ) { super(); }

  ngOnInit() {
	  this.scrollEvent = ((ev) => this.scroll(ev));
	this.userGuideService.getUserGuide()
	  .pipe(takeUntil(this._destroyed))
	  .subscribe(response => {
		const blob = new Blob([response.body], { type: 'text/html' });
		this.readBlob(blob);

	  });
  }

  ngAfterViewChecked(): void {
	this.parse();
}

  readBlob(blob: Blob) {
	const fr = new FileReader();
	fr.onload = ev => {
		this.guideHTML = this.sanitizer.bypassSecurityTrustHtml(fr.result as string);
		this.parse();
	};
	fr.readAsText(blob);
  }

  scroll(ev: Event) {
    document.getElementById((ev.srcElement as any).getAttribute('path')).scrollIntoView({behavior: 'smooth', block: 'start'});
  }

  private parse() {
	  const specialElements: HTMLCollection = document.getElementsByClassName('href');
	  for (let i = 0; i < specialElements.length; i++) {
		  const element = specialElements.item(i);
		  element.removeEventListener('click', this.scrollEvent);
		  element.addEventListener('click', this.scrollEvent);
	  }
  }

}
