import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Input
} from '@angular/core';

import { AppKey } from '@app/types/app-key.type';
import { LoginSession } from '@app/models/login-session';
import { Subject, combineLatest } from 'rxjs';
import { Store, select } from '@ngrx/store';
import { takeUntil } from 'rxjs/operators';
import {
  LoginSelector,
  ConfigurationSelector
} from '@ucap/ng-store-authentication';
import { LoginResponse } from '@ucap/protocol-authentication';
import { RoomInfo, RoomType } from '@ucap/protocol-room';
import { Dictionary } from '@ngrx/entity';
import {
  RoomUserMap,
  RoomUserShortMap
} from '@ucap/ng-store-chat/lib/store/room/state';
import { RoomSelector } from '@ucap/ng-store-chat';
import { VersionInfo2Response } from '@ucap/api-public';
import { AppChatService } from '@app/services/app-chat.service';
import { I18nService } from '@ucap/ng-i18n';
import {
  TranslatePipe as OrganizationTranslate,
  TranslateService
} from '@ucap/ng-ui-organization';

@Component({
  selector: 'app-sections-group-info',
  templateUrl: './info.section.component.html',
  styleUrls: ['./info.section.component.scss'],

  changeDetection: ChangeDetectionStrategy.OnPush
})
export class InfoSectionComponent implements OnInit, OnDestroy {
  @Input()
  set userSeq(seq: string) {
    this._userSeq = seq;
    this.getInfoByUser(seq);
  }
  get userSeq(): string {
    return this._userSeq;
  }
  // tslint:disable-next-line: variable-name
  _userSeq: string;

  versionInfo2Res: VersionInfo2Response;
  loginRes: LoginResponse;
  isMe = false;

  defaultProfileImage: string;
  defaultProfileImageMulti: string;

  roomList: RoomInfo[];
  roomUsersDictionary: Dictionary<RoomUserMap>;
  roomUsersShortDictionary: Dictionary<RoomUserShortMap>;
  filteredRoomList: RoomInfo[] = [];
  allimRoomList: RoomInfo[] = [];

  organizationTranslate: OrganizationTranslate;

  private ngOnDestroySubject = new Subject<boolean>();

  constructor(
    private appChatService: AppChatService,
    private i18nService: I18nService,
    private translateService: TranslateService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    // language setting
    this.translateService.setDefaultLang(this.i18nService.currentLng);
    this.translateService.use(this.i18nService.currentLng);
    this.organizationTranslate = new OrganizationTranslate(
      this.translateService,
      this.changeDetectorRef
    );

    // default image setting
    this.defaultProfileImage = this.appChatService.defaultProfileImage;
    this.defaultProfileImageMulti = this.appChatService.defaultProfileImage;
  }

  ngOnInit(): void {
    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(ConfigurationSelector.versionInfo2Response)
      )
      .subscribe((versionInfo2Res) => {
        this.versionInfo2Res = versionInfo2Res;
      });

    this.store
      .pipe(takeUntil(this.ngOnDestroySubject), select(LoginSelector.loginRes))
      .subscribe((loginRes) => {
        this.loginRes = loginRes;

        if (
          (!!this.userSeq && this.userSeq === loginRes.userSeq) ||
          !this.userSeq
        ) {
          this.isMe = true;
        } else {
          this.isMe = false;
        }
      });

    combineLatest([
      this.store.pipe(select(RoomSelector.rooms)),
      this.store.pipe(
        select(
          (state: any) =>
            state.chat.room.roomUsers.entities as Dictionary<RoomUserMap>
        )
      ),
      this.store.pipe(
        select(
          (state: any) =>
            state.chat.room.roomUsersShort.entities as Dictionary<
              RoomUserShortMap
            >
        )
      )
    ])
      .pipe(takeUntil(this.ngOnDestroySubject))
      .subscribe(([rooms, roomUsers, roomUsersShort]) => {
        rooms = (rooms || []).filter((info) => info.isJoinRoom);
        this.roomList = rooms.sort((a, b) =>
          a.finalEventDate < b.finalEventDate
            ? 1
            : a.finalEventDate > b.finalEventDate
            ? -1
            : 0
        );

        this.roomUsersDictionary = roomUsers;
        this.roomUsersShortDictionary = roomUsersShort;

        if (!!rooms && rooms.length > 0) {
          this.getInfoByUser(this.userSeq);
        }

        this.changeDetectorRef.detectChanges();
      });
  }

  ngOnDestroy(): void {
    if (!!this.ngOnDestroySubject) {
      this.ngOnDestroySubject.complete();
    }
  }

  getInfoByUser(userSeq: string | number): void {
    // is Me check
    if (!!userSeq && !!this.loginRes && !!this.loginRes.userInfo) {
      if (this.loginRes.userSeq + '' === userSeq + '') {
        this.isMe = true;

        // Allim room list setting
        if (!!this.roomList && this.roomList.length > 0) {
          this.allimRoomList = this.roomList.filter((roomInfo) => {
            return (
              roomInfo.roomType === RoomType.Bot ||
              roomInfo.roomType === RoomType.Allim
            );
          });
        }
      } else {
        this.isMe = false;
      }
    }

    // list setting.
    if (!!this.roomList && this.roomList.length > 0) {
      this.filteredRoomList = this.roomList.filter((roomInfo) => {
        if (!!this.isMe) {
          // mine
          return roomInfo.noReadCnt > 0;
        } else {
          // others
          const roomUsers = !!this.roomUsersDictionary
            ? this.roomUsersDictionary[roomInfo.roomId]
            : undefined;
          const roomUsersShort = !!this.roomUsersShortDictionary
            ? this.roomUsersShortDictionary[roomInfo.roomId]
            : undefined;

          let users = [];
          if (!!roomUsers && roomUsers.userInfos.length > 0) {
            users = roomUsers.userInfos;
          } else if (!!roomUsersShort && roomUsersShort.userInfos.length > 0) {
            users = roomUsersShort.userInfos;
          }

          return (
            users.filter(
              (userInfo) => Number(userInfo.seq + '') === Number(userSeq + '')
            ).length > 0
          );
        }
      });
    }

    this.changeDetectorRef.detectChanges();
  }

  getRoomName(roomInfo: RoomInfo): string {
    if (!roomInfo) {
      return '';
    }

    const roomName = this.appChatService.getRoomName(
      this.organizationTranslate,
      this.loginRes,
      roomInfo,
      this.roomUsersDictionary,
      this.roomUsersShortDictionary
    );

    return roomName;
  }

  getRoomProfileImage(roomInfo: RoomInfo): string {
    let roomImage = '';
    if (!!roomInfo) {
      roomImage = this.appChatService.getRoomProfileImage(
        roomInfo,
        this.loginRes,
        this.roomUsersDictionary,
        this.roomUsersShortDictionary
      );
    }

    return roomImage;
  }

  onClickRoomItem(event: MouseEvent, roomInfo: RoomInfo): void {
    event.preventDefault();
    event.stopPropagation();

    console.log('OPEN CHAT ROOM / Group / Main');
  }
}
