import 'package:hmg_nurses/exceptions/api_exception.dart';
import 'package:hmg_nurses/main.dart';
import 'package:hmg_nurses/model/login/project_info_model.dart';
import 'package:hmg_nurses/services/api_client.dart';
import 'package:hmg_nurses/classes/consts.dart';
import 'package:hmg_nurses/model/base/generic_response_model.dart';
import 'package:hmg_nurses/model/login/imei_details_model.dart';
import 'package:injector/injector.dart';

import '../services/firebase_service.dart';

abstract class ILoginApiRepo {
  Future<List<GetIMEIDetailsModel>> getDeviceInfoByIMEI();

  Future<List<ProjectInfoModel>> getProjectInfo(String userId);

  Future memberLogin(String userId, String password, int projectId);
}

class LoginApiRepo implements ILoginApiRepo {
  final IFirebaseService _firebaseService = Injector.appInstance.get<IFirebaseService>();

  @override
  Future<List<GetIMEIDetailsModel>> getDeviceInfoByIMEI() async {
    String url = "${ApiConsts.baseUrlServices}DoctorApplication.svc/REST/DoctorApp_GetDeviceDetailsByIMEI";
    String token = await _firebaseService.getFirebaseToke();
    logger.d("firebase_token: " + token);

    Map<String, dynamic> postParams = {};
    postParams.addAll(appState.postParamsJson);
    postParams["stamp"] = DateTime.now().toIso8601String();
    postParams["IMEI"] = token;
    GenericResponseModel response;
    try {
      response = await Injector.appInstance.get<IApiClient>().postJsonForObject((json) => GenericResponseModel.fromJson(json), url, postParams);
    } catch (e) {
      rethrow;
    }
    return response.listDoctorDeviceDetails ?? [];
  }

  @override
  Future<List<ProjectInfoModel>> getProjectInfo(String userId) async {
    String url = "${ApiConsts.baseUrlServices}DoctorApplication.svc/REST/GetProjectInfo";

    Map<String, dynamic> postParams = {};
    postParams.addAll(appState.postParamsJson);
    postParams["MemberID"] = "13777";
    GenericResponseModel response;
    try {
      response = await Injector.appInstance.get<IApiClient>().postJsonForObject((json) => GenericResponseModel.fromJson(json), url, postParams);
    } catch (e) {
      rethrow;
    }
    return response.projectInfo ?? [];
  }

  @override
  Future memberLogin(String userId, String password, int projectId) async {
    String url = "${ApiConsts.baseUrlServices}Sentry.svc/REST/MemberLogIN_New";

    Map<String, dynamic> postParams = {};
    postParams.addAll(appState.postParamsJson);
    postParams["UserID"] = userId;
    postParams["Password"] = password;
    postParams["ProjectID"] = projectId;
    GenericResponseModel response;
    try {
      response = await Injector.appInstance.get<IApiClient>().postJsonForObject((json) => GenericResponseModel.fromJson(json), url, postParams);
    } catch (e) {
      rethrow;
    }
    return response;
  }
}
