import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { MarkdownEditorComponent } from '../markdown-editor.component';

declare var twemoji;

@Component({
  selector: 'app-emoji-shortcode-picker',
  templateUrl: './emoji-shortcode-picker.component.html',
  styleUrls: ['./emoji-shortcode-picker.component.scss']
})
export class EmojiShortcodePickerComponent implements OnInit {

  /**
   * Dict {shortcode: unicode}
   */
  @Input('shortcodes') shortcodes: any;

  /**
   * event, it triggers, when the user select an emoji via component
   * @paranm $event: {
   *    shortcode: string
   *    emojiSrc: twemoji src of the actual emoji
   *    emoji: unicode emoji
   * }
   */
  @Output('select') onSelect = new EventEmitter<string>();
  hint = [];
  maxHint = 10;

  /**
   * Incoming prefix of the emoji without ":"
   */
  @Input('prefix') set prefix(prefix: string){
    this.hint = [];
    if (prefix && prefix.length > 1){
      for(let key in this.shortcodes){
        if (this.hint.length == 10) break;

        if (key.startsWith(prefix)){
          let src;
          twemoji.parse(this.shortcodes[key], {
            callback:(icon, options)=>{
              src = icon;
            }
          });
          let emojiSrc = MarkdownEditorComponent.emojiUrl+src+"."+MarkdownEditorComponent.emojiExt;
          this.hint.push({
            shortcode: key, 
            emojiSrc: emojiSrc, 
            emoji: this.shortcodes[key]
          });
        }
      }
    }
  }

  constructor() { }

  ngOnInit(): void {
  }

  public selectEmoji(emoji){
    this.onSelect.emit(emoji);
  }

}
