import PlatformDetectionService from './platform-detection.service';
import {Strings, Subject, ReadOnlySubject} from '@techniker-me/tools';
import {PhenixWebSocket, PhenixWebSocketStatus, PhenixWebSocketMessage} from 'services/net/PhenixWebSocket';
import config from 'config';

class AuthenticationService {
  private static readonly _instance: AuthenticationService = new AuthenticationService();
  private readonly _phenixWebSocket: Subject<PhenixWebSocket | null> = new Subject(null);
  private readonly _sessionId: string = Strings.random(10);

  public static getInstance(): AuthenticationService {
    return AuthenticationService._instance;
  }

  get status(): ReadOnlySubject<PhenixWebSocketStatus> | undefined {
    return this._phenixWebSocket.value?.status || undefined;
  }

  public setWebSocketUri(webSocketUri: string): void {
    this._phenixWebSocket.value?.dispose();
    this._phenixWebSocket.value = new PhenixWebSocket(webSocketUri);
  }

  public async authenticateCredentials(applicationId: string, secret: string): Promise<{error: unknown; response: unknown}> {
    const authenicate = {
      applicationId,
      secret,
      clientVersion: config.controlCenterVersion,
      deviceId: '',
      platform: PlatformDetectionService.platform,
      platformVersion: PlatformDetectionService.platformVersion,
      sessionId: this._sessionId,
      authenticationToken: secret
    };

    return this._phenixWebSocket.value?.sendMessage(PhenixWebSocketMessage.Authenticate, authenicate) as Promise<{error: unknown; response: unknown}>;
  }

  public async signout(): Promise<{error: unknown; response: unknown}> {
    const {error, response} = await (this._phenixWebSocket.value?.sendMessage(PhenixWebSocketMessage.Bye, {sessionId: this._sessionId}) as Promise<{
      error: unknown;
      response: unknown;
    }>);

    return {error, response};
  }
}

export default AuthenticationService.getInstance();
