import { Injectable, Inject, NgZone } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import {
  UCAP_NATIVE_SERVICE,
  NativeService,
  UpdateCheckConfig
} from '@ucap-webmessenger/native';
import { Store } from '@ngrx/store';
import { NGXLogger } from 'ngx-logger';

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 { PublicApiService } from '@ucap-webmessenger/api-public';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import {
  LoginInfo,
  KEY_LOGIN_INFO,
  EnvironmentsInfo,
  KEY_ENVIRONMENTS_INFO
} from '@app/types';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AppNativeService {
  constructor(
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService,
    private publicApiService: PublicApiService,
    private sessionStorageService: SessionStorageService,
    @Inject(DOCUMENT) private document: Document,
    private ngZone: NgZone,
    private store: Store<any>,
    private logger: NGXLogger
  ) {}

  subscribe(): void {
    this.nativeService.logout().subscribe(() => {
      this.ngZone.run(() => {
        this.store.dispatch(AuthenticationStore.logoutConfirmation());
      });
    });
    this.nativeService.changeStatus().subscribe(statusCode => {});
    this.nativeService.showSetting().subscribe(() => {
      this.ngZone.run(() => {
        this.store.dispatch(SettingsStore.showDialog());
      });
    });
  }

  subscribeAfterLogin(): void {
    const loginInfo = this.sessionStorageService.get<LoginInfo>(KEY_LOGIN_INFO);
    const environmentsInfo = this.sessionStorageService.get<EnvironmentsInfo>(
      KEY_ENVIRONMENTS_INFO
    );

    const els = this.document.getElementsByTagName('app-root');

    const currentVersion = els.item(0).getAttribute('app-version');

    const updateCheckConfig: UpdateCheckConfig = {
      feed: this.publicApiService.urlForVersionInfo2({
        deviceType: environment.productConfig.updateCheckConfig.deviceType,
        companyGroupType: loginInfo.companyGroupType,
        companyCode: loginInfo.companyCode,
        loginId: loginInfo.loginId
      }),
      currentVersion,
      intervalHour: environment.productConfig.updateCheckConfig.intervalHour
    };

    this.nativeService
      .checkForInstantUpdates(updateCheckConfig)
      .subscribe(updateInfo => {
        this.store.dispatch(UpdateStore.existInstantUpdate({ updateInfo }));
      });
  }
}
