import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, Renderer2, ViewChild } from '@angular/core';

declare var twemoji;

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

  public categories = [
    {name: 'Emotions', emojies: [], icon:'emoji_emotions'},
    {name: 'People', emojies: [], icon:'emoji_people'},
    {name: 'Skin & Hair', emojies: [], icon:'color_lens'},
    {name: 'Pets', emojies: [], icon:'emoji_nature'},
    {name: 'Foods & Drinks', emojies: [], icon:'emoji_food_beverage'},
    {name: 'Transportation', emojies: [], icon:'emoji_transportation'},
    {name: 'Events', emojies: [], icon:'emoji_events'},
    {name: 'Objects', emojies: [], icon:'emoji_objects'},
    {name: 'Symbols', emojies: [], icon:'emoji_symbols'},
    {name: 'Flags', emojies: [], icon:'emoji_flags'},
  ];

  public shortcodes;
  public someData;

  // for lazyload, it is a gray rectangle
  public defaultImage = "assets/img/twemoji/13.0.1/72x72/1f532.png";
  
  /**
   * The selected current group, for the header, ex: emoji_nature
   */
  public activeGroup = '';

  /**
   * Emoji from emojibase
   */
  @Input('allEmoji') allEmoji;

  @Output('select') selectEmojiEvent = new EventEmitter<string>();
  @ViewChild('emojiCollection') emojiCollectionNode: ElementRef;
  onScrollEvent;

  constructor(private renderer: Renderer2) {
  }

  /**
   * scroll into the group
   * @param group group icon name: emoji_nature
   */
  jumpToGroup(group){
    let element = this.emojiCollectionNode.nativeElement.querySelector('[data-group="'+group+'"]');
    if (element){
      let y = element.offsetTop;
      this.emojiCollectionNode.nativeElement.scrollTo(0, y, { behavior: 'smooth'});
    }
    
  }

  ngOnInit(): void {
    
  }

 

  ngAfterViewInit(): void{
    
    // init all the emoji
    for(let i = 0; i < this.allEmoji.length; i++){
      twemoji.parse(this.allEmoji[i].emoji, {
        callback:(icon, options)=>{
          if (icon){
            let emoji = this.allEmoji[i];
            emoji.twitter = icon;
            
            if (i < 26) emoji.group = 8; // put the A-Z letters into the symbols
            if (!emoji.group) emoji.group = 0; // zero groups emojies doesn't have group attr

            
            if (!this.categories[emoji.group]) this.categories[emoji.group] = { name: 'Untitled', emojies: [], icon: 'insert_photo'}; // expand the categories
            this.categories[emoji.group].emojies.push(emoji);
            
          }
        }
      });
    }

    // detect on which group you are
    this.onScrollEvent = (event)=>{
      let y = this.emojiCollectionNode.nativeElement.scrollTop;
      let childs = this.emojiCollectionNode.nativeElement.childNodes;
      for(let i = 0; i < childs.length; i++){
        if (childs[i].offsetTop - 5 <= y && childs[i].offsetTop+childs[i].offsetHeight > y + 5){
          this.activeGroup = childs[i].dataset.group;
          return;
        }
      }
    };



    /**
     * <div *ngFor="let group of categories" class="group" [attr.data-group]="group.icon">
            <div class="group-name"><a id="{{group.icon}}">{{group.name}}</a></div>
            <div class="emoji-list">
                <span *ngFor="let emoji of group.emojies" (click)="selectEmoji(emoji)">
                    <img *ngIf="emoji.twitter" [defaultImage]="defaultImage" [lazyLoad]="'https://twemoji.maxcdn.com/v/13.0.1/72x72/'+emoji.twitter+'.png'"> 
                </span>
            </div>
        </div>
     */
    // ngFor is to slow to generate DOM for 2k emojies
    this.categories.forEach((group)=>{
      let groupNode = this.renderer.createElement('div');
      this.renderer.addClass(groupNode, 'group');
      this.renderer.setAttribute(groupNode, 'data-group', group.icon);

      let groupTitleNode = this.renderer.createElement('div');
      this.renderer.addClass(groupTitleNode, 'group-name');

      let groupLink = this.renderer.createElement('a');
      this.renderer.setProperty(groupLink, 'id', group.icon);
      this.renderer.setProperty(groupLink, 'innerHTML', group.name);

      let emojiList = this.renderer.createElement('div');
      this.renderer.addClass(emojiList, 'emoji-list');

      this.renderer.appendChild(groupTitleNode, groupLink);
      this.renderer.appendChild(groupNode, groupTitleNode);
      this.renderer.appendChild(groupNode, emojiList);

      group.emojies.forEach((emoji)=>{
        
        if (emoji.hasOwnProperty('twitter')){
          let emojiNode = this.renderer.createElement('span');
          emojiNode.addEventListener('click', ()=>{
            this.selectEmoji(emoji)
          })
          let emojiImage = this.renderer.createElement('img');
          this.renderer.setProperty(emojiImage, 'loading', 'lazy');
          this.renderer.setProperty(emojiImage, 'src', 'assets/img/twemoji/13.0.1/72x72/'+emoji.twitter+'.png');
          
          
          this.renderer.appendChild(emojiNode, emojiImage);
          this.renderer.appendChild(emojiList, emojiNode);
        }
        
      })


      this.renderer.appendChild(this.emojiCollectionNode.nativeElement, groupNode);
    })

    this.emojiCollectionNode.nativeElement.addEventListener('scroll', this.onScrollEvent);
  }

  ngOnDestroy(): void{
    this.emojiCollectionNode.nativeElement.removeEventListener('scroll', this.onScrollEvent);
  }

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

}
