import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import {
  StickerInfo,
  StickerFilesInfo,
  StickerUtil,
  StickerMap
} from '@ucap-webmessenger/core';

@Component({
  selector: 'ucap-sticker-selector',
  templateUrl: './sticker-selector.component.html',
  styleUrls: ['./sticker-selector.component.scss']
})
export class StickerSelectorComponent implements OnInit {
  @Input()
  stickerHistory: string[] = [];

  @Output()
  selectedSticker = new EventEmitter<StickerFilesInfo>();

  @Output()
  closeSticker = new EventEmitter();

  stickerBasePath = 'assets/sticker/';
  stickerInfoList: StickerInfo[] = [];
  stickerFileInfoList: StickerFilesInfo[] = [];
  currentSticker: StickerFilesInfo;

  currentTabIndex: number;

  constructor() {}

  ngOnInit() {
    this.stickerInfoList = StickerUtil.getStickerInfoList();
    this.currentTabIndex = 0;
  }

  onSelectedIndexChange(value: number) {
    this.currentTabIndex = value;
  }

  getStickerTitleImage(
    stickerInfo: StickerInfo,
    hover: boolean,
    tabIndex: number
  ) {
    if (this.currentTabIndex === tabIndex) {
      return this.stickerBasePath + stickerInfo.iconPathOn;
    }

    if (!hover) {
      return this.stickerBasePath + stickerInfo.iconPath;
    } else {
      return this.stickerBasePath + stickerInfo.iconPathOn;
    }
  }

  getStickerInfos(stickerInfo: StickerInfo) {
    if (stickerInfo.index === '00') {
      const rtnArray: StickerFilesInfo[] = [];

      if (!!this.stickerHistory && this.stickerHistory.length > 0) {
        this.stickerHistory.forEach(sticker => {
          const arr: string[] = sticker.split('_');
          if (arr.length === 2) {
            const sInfo: StickerInfo[] = StickerMap.filter(
              s => s.index === arr[0]
            );
            if (!!sInfo && sInfo.length > 0) {
              rtnArray.push(
                ...sInfo[0].fileInfos.filter(
                  fileInfo => fileInfo.index === sticker
                )
              );
            }
          }
        });
      }
      return rtnArray;
    } else {
      return stickerInfo.fileInfos;
    }
  }

  getStickerContentsImage(sticker: StickerFilesInfo) {
    return this.stickerBasePath + sticker.path;
  }

  onClickSelectSticker(sticker: StickerFilesInfo) {
    this.currentSticker = sticker;
    this.selectedSticker.emit(sticker);
  }

  onClickClose() {
    this.closeSticker.emit();
  }
}
