import { Injectable, Inject } from '@angular/core';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
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';
import { TranslateService as UCapTranslateService } from '@ucap-webmessenger/ui';
import { DateService as UCapDateService } from '@ucap-webmessenger/ui';
import { TranslateService } from '@ngx-translate/core';
import { EnviromentsService } from '@ucap-webmessenger/enviroments';
import { NGXLogger } from 'ngx-logger';

@Injectable()
export class AppService {
  constructor(
    private enviromentsService: EnviromentsService,
    private sessionStorageService: SessionStorageService,
    private appNotificationService: AppNotificationService,
    private appNativeService: AppNativeService,
    private translateService: TranslateService,
    private ucapTranslateService: UCapTranslateService,
    private ucapDateService: UCapDateService,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService,
    private logger: NGXLogger
  ) {
    this.translateService.setDefaultLang('ko');
    this.translateService.use('ko');

    this.ucapTranslateService.setDefaultLang('ko');
    this.ucapTranslateService.use('ko');

    this.ucapDateService.setDefaultTimezone('Asia/Seoul');
    this.ucapDateService.use('Asia/Seoul');
    this.ucapDateService.setLocale(this.translateService.currentLang);
  }

  public postInit(): Promise<any> {
    const initPromise = new Promise<void>((resolve, reject) => {
      try {
        let deviceType: DeviceType;
        if (this.enviromentsService.nodeWebkit()) {
          deviceType = DeviceType.PC;
        } else if (this.enviromentsService.android()) {
          deviceType = DeviceType.Android;
        } else if (this.enviromentsService.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]);
  }
}
