import { Subject } from 'rxjs';
import { takeUntil, take, map, withLatestFrom, tap } from 'rxjs/operators';

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

import { Store, select } from '@ngrx/store';

import { LoginResponse } from '@ucap/protocol-authentication';
import { AuthResponse, UserInfoSS } from '@ucap/protocol-query';

import { LogService } from '@ucap/ng-logger';
import {
  LoginSelector,
  AuthorizationSelector,
  ConfigurationSelector,
  LoginActions
} from '@ucap/ng-store-authentication';
import { VersionInfo2Response } from '@ucap/api-public';
import { QueryProtocolService } from '@ucap/ng-protocol-query';
import { PresenceType, StatusCode } from '@ucap/core';
import { PresenceSelector } from '@ucap/ng-store-organization';
import { StatusBulkInfo } from '@ucap/protocol-status';
import { I18nService } from '@ucap/ng-i18n';
import { FileUploadItem } from '@ucap/api';
import { BuddySelector, BuddyActions } from '@ucap/ng-store-group';

import { UserInfoUpdateType } from '@ucap/protocol-info';
@Component({
  selector: 'app-organization-profile-01',
  templateUrl: './profile-01.component.html',
  styleUrls: ['./profile-01.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class Profile01Component implements OnInit, OnDestroy {
  @Input()
  set userSeq(seq: string) {
    this._userSeq = seq;
    if (!!this.loginRes) {
      this.refreshProfile();
    }
  }
  get userSeq(): string {
    return this._userSeq;
  }
  _userSeq: string;

  @ViewChild('profileImageFileInput', { static: false })
  profileImageFileInput: ElementRef<HTMLInputElement>;

  profileImageFileUploadItem: FileUploadItem;

  userInfo: UserInfoSS;

  loginRes: LoginResponse;
  authRes: AuthResponse;
  versionInfo2Res: VersionInfo2Response;
  presence: StatusBulkInfo;

  String = String;

  private ngOnDestroySubject: Subject<void>;

  constructor(
    private queryProtocolService: QueryProtocolService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService,
    private i18nService: I18nService
  ) {}

  isBuddy = false;
  PresenceType = PresenceType;
  isFavorite = false;
  ngOnInit(): void {
    this.ngOnDestroySubject = new Subject();

    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;
        this.userSeq = this.loginRes.userSeq;
      });

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(AuthorizationSelector.authResponse)
      )
      .subscribe((authRes) => {
        this.authRes = authRes;
      });

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(PresenceSelector.selectEntitiesStatusBulkInfo)
      )
      .subscribe((statusBulkInfo) => {
        this.presence = !!statusBulkInfo
          ? statusBulkInfo[this.userSeq]
          : undefined;
      });
  }

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

  getPresence(type: PresenceType): string {
    let status: string;
    let rtnClass = '';
    switch (type) {
      case PresenceType.PC:
        status = !!this.presence ? this.presence.pcStatus : undefined;
        break;
      case PresenceType.MOBILE:
        status = !!this.presence ? this.presence.mobileStatus : undefined;
        break;
    }

    switch (status) {
      case StatusCode.OnLine:
        rtnClass = 'online';
        break;
      case StatusCode.Away:
        rtnClass = 'absence';
        break;
      case StatusCode.Busy:
        rtnClass = 'other-business';
        break;
      default:
        rtnClass = 'offline';
        break;
    }

    return rtnClass;
  }

  getPresenceMsg(): string {
    let presenceMsg = this.i18nService.t('presence.offline');

    if (!!this.presence) {
      switch (this.presence.pcStatus) {
        case StatusCode.OnLine:
          presenceMsg = this.i18nService.t('presence.online');
          break;
        case StatusCode.Away:
          presenceMsg = this.i18nService.t('presence.away');
          break;
        case StatusCode.Busy:
          if (
            !!this.presence.statusMessage &&
            this.presence.statusMessage !== '.'
          ) {
            presenceMsg = this.presence.statusMessage;
          } else {
            presenceMsg = this.i18nService.t('presence.statusMessage1');
          }
          break;
      }
    }

    return presenceMsg;
  }

  refreshProfile() {
    this.queryProtocolService
      .dataUser({
        divCd: 'OPENPROF',
        seq: Number(this.userSeq),
        senderCompanyCode: this.loginRes.userInfo.companyCode,
        senderEmployeeType: this.loginRes.userInfo.employeeType
      })
      .pipe(
        take(1),
        withLatestFrom(this.store.pipe(select(BuddySelector.buddies))),
        tap(([res, buddies]) => {
          this.userInfo = res.userInfo;
          const users = buddies.filter(
            (buddy) => buddy.seq + '' === this.userInfo.seq
          );
          this.isBuddy = users.length > 0;
          if (this.isBuddy) {
            this.isFavorite = users[0].isFavorit;
          }
          this.changeDetectorRef.detectChanges();
        })
      )
      .subscribe();
  }
  onProfileImageView() {}
  onChangeFileInput() {}
  onChangeIntro(intro: string) {
    console.log(intro);
    this.store.dispatch(
      LoginActions.infoUser({
        req: {
          type: UserInfoUpdateType.Intro,
          info: intro
        }
      })
    );
  }
  onChangeNickname(nickname: string) {
    console.log(nickname);
  }

  onToggleFavorite(params: { userInfo: UserInfoSS; isFavorite: boolean }) {
    this.store.dispatch(
      BuddyActions.update({
        req: { seq: Number(params.userInfo.seq), isFavorit: params.isFavorite }
      })
    );
  }
  onToggleBuddy(params: { userInfo: UserInfoSS; isBuddy: boolean }) {}
  onOpenChat(userInfo: UserInfoSS) {}
  onSendCall(calleeNumber: string) {}
  onSendSms(smsNum: string) {}
  onCreateConference(userSeq: number) {}
  onSendMessage(userInfo: UserInfoSS) {}

  onUploadProfileImage(profileImageFileUploadItem: FileUploadItem) {}
}
