import 'dart:async';
import 'dart:convert';

import '../../../../model/accountData.dart';
import '../../webuntisApi.dart';
import 'authenticateParams.dart';
import 'authenticateResponse.dart';

class Authenticate extends WebuntisApi {
  AuthenticateParams param;

  Authenticate(this.param) : super("authenticate", param, authenticatedResponse: false);

  @override
  Future<AuthenticateResponse> run() async {
    awaitingResponse = true;
    String rawAnswer = await query(this);
    AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result']));
    _lastResponse = response;
    if(!awaitedResponse.isCompleted) awaitedResponse.complete();
    return response;
  }

  static bool awaitingResponse = false;
  static Completer awaitedResponse = Completer();
  static AuthenticateResponse? _lastResponse;

  static Future<void> createSession() async {
    _lastResponse = await Authenticate(
        AuthenticateParams(
          user: AccountData().getUsername(),
          password: AccountData().getPassword(),
        )
    ).run();
  }

  static Future<AuthenticateResponse> getSession() async {
    if(awaitingResponse) {
      await awaitedResponse.future;
    }

    if(_lastResponse == null) {
      awaitingResponse = true;
      await createSession();
    }
    return _lastResponse!;

  }
}