import { Injectable, Inject } from '@angular/core';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { EnviromentUtilService } from '@ucap-webmessenger/util';
import { DeviceType } from '@ucap-webmessenger/core';
import { EnvironmentsInfo, KEY_ENVIRONMENTS_INFO } from '@app/types';
import { AppNotificationService } from './notification.service';
import { NativeService, UCAP_NATIVE_SERVICE } from '@ucap-webmessenger/native';
import { AppNativeService } from './native.service';

@Injectable()
export class AppService {
  constructor(
    private enviromentUtilService: EnviromentUtilService,
    private sessionStorageService: SessionStorageService,
    private appNotificationService: AppNotificationService,
    private appNativeService: AppNativeService,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService
  ) {}

  public postInit(): Promise<any> {
    const initPromise = new Promise<void>((resolve, reject) => {
      try {
        let deviceType: DeviceType;
        if (this.enviromentUtilService.nodeWebkit()) {
          deviceType = DeviceType.PC;
        } else if (this.enviromentUtilService.android()) {
          deviceType = DeviceType.Android;
        } else if (this.enviromentUtilService.ios()) {
          deviceType = DeviceType.iOS;
        } else {
          deviceType = DeviceType.Web;
        }

        this.sessionStorageService.set<EnvironmentsInfo>(
          KEY_ENVIRONMENTS_INFO,
          {
            deviceType
          }
        );

        this.appNativeService.subscribe();
        this.appNotificationService.subscribe();
        this.nativeService.postAppInit();
        resolve();
      } catch (error) {
        reject();
      }
    });

    return Promise.all([initPromise]);
  }
}
