import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import {
  StickerInfo,
  StickerFilesInfo,
  StickerUtil,
  StickerMap
} from '@ucap-webmessenger/core';
import { LocalStorageService } from '@ucap-webmessenger/web-storage';
import { KEY_STICKER_HISTORY } from '@app/types';

@Component({
  selector: 'ucap-sticker-selector',
  templateUrl: './sticker-selector.component.html',
  styleUrls: ['./sticker-selector.component.scss']
})
export class StickerSelectorComponent implements OnInit {
  @Output()
  selectedSticker = new EventEmitter<StickerFilesInfo>();

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

  currentTabIndex: number;

  constructor(private localStorageService: LocalStorageService) {}

  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[] = [];
      const history = this.localStorageService.get<string[]>(
        KEY_STICKER_HISTORY
      );
      if (!!history && history.length > 0) {
        history.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);
  }
}
