import {
  Component,
  OnInit,
  Input,
  Inject,
  ElementRef,
  AfterViewInit
} from '@angular/core';
import { Info, StickerEventJson } from '@ucap-webmessenger/protocol-event';
import { NGXLogger } from 'ngx-logger';
import { StickerInfo } from '../../models/sticker-info.json';
import { UCAP_NATIVE_SERVICE, NativeService } from '@ucap-webmessenger/native';

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

  contents: string;
  stickerUrl?: string;
  constructor(
    private logger: NGXLogger,
    private elementRef: ElementRef,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService
  ) {}

  ngOnInit() {
    try {
      if (!!this.message.sentMessageJson.file) {
        this.stickerUrl = `assets/sticker/sticker_s_${this.message.sentMessageJson.file}.png`;
      }
      if (!!this.message.sentMessageJson.chat) {
        this.contents = this.message.sentMessageJson.chat;
      }
    } catch (e) {
      this.logger.error(e);
    }
  }

  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
    );
  }
}
