import {
  Component,
  OnInit,
  Input,
  ElementRef,
  AfterViewInit,
  Inject,
  Output,
  EventEmitter
} from '@angular/core';
import {
  StickerInfo,
  StickerFilesInfo,
  StickerUtil,
  StickerMap,
  ActiveAndOrdering,
  KEY_STICKER_HISTORY
} from '@ucap/ng-core';
import { LocalStorageService } from '@ucap/ng-web-storage';

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

  @Output()
  closeSticker = new EventEmitter();

  stickerHistory: string[] = [];

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

  currentTabIndex: number;

  customStickerMap: StickerInfo[] = [...StickerMap];
  activeAndOrdering: string[] = [...ActiveAndOrdering];

  constructor(private localStorageService: LocalStorageService) {}

  ngOnInit() {
    this.stickerHistory = this.localStorageService.get<string[]>(
      KEY_STICKER_HISTORY
    );

    this.stickerInfoList = StickerUtil.getStickerInfoList(
      this.customStickerMap,
      this.activeAndOrdering
    );
    this.currentTabIndex = 0;
  }

  ngAfterViewInit(): void {}

  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[] = this.customStickerMap.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();
  }
}
