import {
  Component,
  OnInit,
  Input,
  ElementRef,
  AfterViewInit,
  Inject
} from '@angular/core';
import { Info, EventJson } from '@ucap-webmessenger/protocol-event';
import { NativeService, UCAP_NATIVE_SERVICE } from '@ucap-webmessenger/native';

@Component({
  selector: 'ucap-chat-message-box-text',
  templateUrl: './text.component.html',
  styleUrls: ['./text.component.scss']
})
export class TextComponent implements OnInit, AfterViewInit {
  @Input()
  message: Info<EventJson>;

  constructor(
    private elementRef: ElementRef,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService
  ) {}

  ngOnInit() {}

  ngAfterViewInit(): void {
    if (
      !!this.elementRef.nativeElement &&
      !!this.elementRef.nativeElement.querySelector('a')
    ) {
      const elements = this.elementRef.nativeElement.querySelectorAll('a');
      elements.forEach(element => {
        element.addEventListener('click', this.onClickEvent.bind(this));
      });
    }
  }

  onClickEvent(event: MouseEvent) {
    this.nativeService.openDefaultBrowser(
      (event.target as HTMLAnchorElement).text
    );
  }
}
