import { Component, OnInit, Inject, OnDestroy } from '@angular/core';
import {
  UCAP_NATIVE_SERVICE,
  NativeService,
  WindowState,
  UpdateInfo
} from '@ucap-webmessenger/native';
import { Observable, Subscription, of } from 'rxjs';
import { Store, select } from '@ngrx/store';

import * as AppStore from '@app/store';
import * as ChatStore from '@app/store/messenger/chat';
import * as AuthenticationStore from '@app/store/account/authentication';
import * as SettingsStore from '@app/store/messenger/settings';
import * as UpdateStore from '@app/store/setting/update';

import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { tap, take, map, catchError } from 'rxjs/operators';
import {
  RightDrawer,
  KEY_URL_INFO,
  LoginInfo,
  KEY_LOGIN_INFO,
  KEY_LOGIN_RES_INFO,
  KEY_VER_INFO
} from '@app/types';
import {
  WebLink,
  DaesangUrlInfoResponse
} from '@ucap-webmessenger/api-external';
import {
  SessionStorageService,
  LocalStorageService
} from '@ucap-webmessenger/web-storage';
import { AppUserInfo, KEY_APP_USER_INFO } from '@app/types/app-user-info.type';
import { environment } from '../../../../environments/environment';
import {
  DaesangApiService,
  DaesangProtocolService,
  WebLinkType
} from '@ucap-webmessenger/daesang';
import { NGXLogger } from 'ngx-logger';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';
import {
  ProfileDialogComponent,
  ProfileDialogResult,
  ProfileDialogData
} from '@app/layouts/messenger/dialogs/profile/profile.dialog.component';
import { DialogService } from '@ucap-webmessenger/ui';

@Component({
  selector: 'app-layout-native-top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.scss']
})
export class TopBarComponent implements OnInit, OnDestroy {
  windowStateChanged$: Observable<WindowState>;
  WindowState = WindowState;

  loginRes: LoginResponse;
  loginResSubscription: Subscription;
  sessionVerinfo: VersionInfo2Response;

  updateInfo$: Observable<UpdateInfo>;

  loginInfo: LoginInfo;
  weblink: WebLink[] = [];
  webLinkBadgeMail = 0;
  webLinkBadgePayment = 0;

  WebLinkType = WebLinkType;

  constructor(
    private store: Store<any>,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService,
    private dialogService: DialogService,
    private localStorageService: LocalStorageService,
    private sessionStorageService: SessionStorageService,
    private daesangApiService: DaesangApiService,
    private daesangProtocolService: DaesangProtocolService,
    private logger: NGXLogger
  ) {}

  ngOnInit() {
    this.windowStateChanged$ = this.nativeService.windowStateChanged();

    this.loginResSubscription = this.store
      .pipe(
        select(AppStore.AccountSelector.AuthenticationSelector.loginRes),
        tap(loginRes => {
          this.loginRes = loginRes;

          this.loginInfo = this.sessionStorageService.get<LoginInfo>(
            KEY_LOGIN_INFO
          );

          this.sessionVerinfo = this.sessionStorageService.get<
            VersionInfo2Response
          >(KEY_VER_INFO);

          // WebLink init..
          this.initWebLink();
        })
      )
      .subscribe();

    this.updateInfo$ = this.store.pipe(
      select(AppStore.SettingSelector.UpdateSelector.updateInfo)
    );
  }

  initWebLink(): void {
    const loginRes = this.sessionStorageService.get<LoginResponse>(
      KEY_LOGIN_RES_INFO
    );

    const urlInfo: DaesangUrlInfoResponse = this.sessionStorageService.get<
      DaesangUrlInfoResponse
    >(KEY_URL_INFO);

    if (!!urlInfo && !!urlInfo.webLink) {
      this.weblink = urlInfo.webLink.filter(
        weblink =>
          urlInfo.webLinkAllowedList.filter(type => type === weblink.key)
            .length > 0
      );

      if (urlInfo.webLinkAllowedList.indexOf(WebLinkType.Mail) > -1) {
        // 메일 카운트 체크.
        const link = urlInfo.webLink.filter(
          weblink => weblink.key === WebLinkType.MailCnt
        );
        if (link.length > 0) {
          const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
            KEY_APP_USER_INFO,
            environment.customConfig.appKey
          );

          const WebLinkMailCnt = link[0];
          const loginPw = appUserInfo.loginPw;
          const loginPw2 = this.loginInfo.loginPw;
          const loginId = this.loginInfo.loginId;
          const token = loginRes.tokenString;

          const url = WebLinkMailCnt.url
            .replace(/(\(%USER_TOKEN%\))/g, token)
            .replace(/(\(%USER_ID%\))/g, loginId)
            .replace(/(\(%USER_PASS%\))/g, loginPw);

          this.daesangApiService
            .retrieveMailCount(url)
            .pipe(
              take(1),
              map(res => (this.webLinkBadgeMail = res.count)),
              catchError(error => of(this.logger.log(error)))
            )
            .subscribe();
        }
      }
      if (urlInfo.webLinkAllowedList.indexOf(WebLinkType.Payment) > -1) {
        // 결제 카운트 체크.
        const link = urlInfo.webLink.filter(
          weblink => weblink.key === WebLinkType.PaymentCnt
        );
        if (link.length > 0) {
          const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
            KEY_APP_USER_INFO,
            environment.customConfig.appKey
          );

          const WebLinkPaymentCnt = link[0];
          const loginPw = appUserInfo.loginPw;
          const loginPw2 = this.loginInfo.loginPw;
          const loginId = this.loginInfo.loginId;
          const token = loginRes.tokenString;

          const url = WebLinkPaymentCnt.url
            .replace(/(\(%USER_TOKEN%\))/g, token)
            .replace(/(\(%USER_ID%\))/g, loginId)
            .replace(/(\(%USER_PASS%\))/g, loginPw);

          this.daesangApiService
            .retrievePaymentCount(url)
            .pipe(
              take(1),
              map(res => {
                this.webLinkBadgePayment = res.count;
              }),
              catchError(error => of(this.logger.log(error)))
            )
            .subscribe();
        }
      }
    }
  }

  ngOnDestroy(): void {
    if (!!this.loginResSubscription) {
      this.loginResSubscription.unsubscribe();
    }
  }

  onClickClose() {
    this.nativeService.windowClose();
  }

  onClickMinimize() {
    this.nativeService.windowMinimize();
  }

  onClickMaxmize() {
    this.nativeService.windowMaximize();
  }

  onClickSettings(): void {
    this.store.dispatch(SettingsStore.showDialog());
  }

  onClickLogout(): void {
    this.store.dispatch(AuthenticationStore.logoutConfirmation());
  }

  getMyProfileImageWidget(): string {
    if (!!this.loginRes) {
      return this.loginRes.userInfo.profileImageFile;
    } else {
      return '';
    }
  }

  onClickOpenProfile(event: Event) {
    // [GROUP]
    // this.queryProtocolService
    //   .dataUser({
    //     divCd: 'OPENPROF',
    //     seq: userInfo.seq,
    //     senderCompanyCode: this.loginRes.userInfo.companyCode,
    //     senderEmployeeType: this.loginRes.userInfo.employeeType
    //   })
    //   .pipe(
    //     take(1),
    //     map(res => {
    //       if (!!res && !!res.userInfo) {
    //         this.dialogService.open<
    //           ProfileDialogComponent,
    //           ProfileDialogData,
    //           ProfileDialogResult
    //         >(ProfileDialogComponent, {
    //           data: {
    //             userInfo: res.userInfo
    //           }
    //         });
    //       }
    //     })
    //   )
    //   .subscribe();
    event.preventDefault();

    this.logger.debug('onClickOpenProfile');
    return;

    // [Daesang]
    this.daesangProtocolService
      .dataUserDaesang({
        divCd: 'OPENPROF',
        seq: this.loginRes.userSeq,
        senderCompanyCode: this.loginRes.userInfo.companyCode,
        senderEmployeeType: this.loginRes.userInfo.employeeType
      })
      .pipe(
        take(1),
        map(res => {
          if (!!res && !!res.userInfo) {
            this.dialogService.open<
              ProfileDialogComponent,
              ProfileDialogData,
              ProfileDialogResult
            >(ProfileDialogComponent, {
              data: {
                userInfo: res.userInfo
              }
            });
          }
        })
      )
      .subscribe();
  }

  onClickNotice(): void {
    this.store.dispatch(
      ChatStore.selectedRightDrawer({
        req: RightDrawer.Notice
      })
    );
  }

  /** About WebLink */
  onClickWebLink(link: WebLink): void {
    const appUserInfo = this.localStorageService.encGet<AppUserInfo>(
      KEY_APP_USER_INFO,
      environment.customConfig.appKey
    );

    const loginPw = appUserInfo.loginPw;
    const loginPw2 = this.loginInfo.loginPw;
    const loginId = this.loginInfo.loginId;
    const token = this.loginRes.tokenString;

    const url = link.url
      .replace(/(\(%USER_TOKEN%\))/g, token)
      .replace(/(\(%USER_ID%\))/g, loginId)
      .replace(/(\(%USER_PASS%\))/g, loginPw);

    this.nativeService.openDefaultBrowser(url);
  }

  onClickUpdate() {
    this.store.dispatch(UpdateStore.applyInstantUpdate());
  }
}