import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/family-file/add_family_file_request.dart';
import 'package:diplomaticquarterapp/core/model/family-file/insert_share_file_request.dart';
import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/Authentication/send_activation_request.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordsByStatusReq.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:flutter/cupertino.dart';

// SharedPreferences sharedPref = new SharedPreferences();
enum APP_STATUS { LOADING, UNAUTHENTICATED, AUTHENTICATED }

AppSharedPreferences sharedPref = new AppSharedPreferences();

const String GET_SHARED_RECORD_BY_STATUS = 'Services/Authentication.svc/REST/GetAllSharedRecordsByStatus';
const String ADD_FAMILY_FILES = 'Services/Patients.svc/REST/ShareFamilyFileService';
const String SEND_FAMILY_FILE_ACTIVATION = 'Services/Authentication.svc/REST/SendActivationCodeForFamilyFile';
const String INSERT_PATIENT_FILE = 'Services/Authentication.svc/REST/Insert_SharePatientFile';
const String CHECK_ACTIVATION_CODE = 'Services/Authentication.svc/REST/CheckActivationCodeForFamilyFile';

const String UPDATE_FILE_STATUS = 'Services/Authentication.svc/REST/Update_FileStatus';
const String REMOVE_FILE_STATUS = 'Services/Authentication.svc/REST/ActiveDeactive_PatientFile';

const String ACTIVATION_CODE_URL = "Services/Authentication.svc/REST/CheckActivationCode";
const String SENT_REQUEST_URL = 'Services/Authentication.svc/REST/GetAllSharedRecordsByStatus';
const String RECEVIED_REQUEST_URL = 'Services/Authentication.svc/REST/GetAllPendingRecordsByResponseId';
const ACCEPT_REJECT_FAMILY = 'Services/Authentication.svc/REST/Update_FileStatus';
const DEACTIVATE_FAMILY = 'Services/Authentication.svc/REST/DeactivateRequestByRensponse';

class FamilyFilesProvider with ChangeNotifier {
  bool isLogin = false;
  bool isLoading = true;
  dynamic authenticatedUser;
  GetAllSharedRecordsByStatusResponse allSharedRecordsByStatusResponse;

  Future<GetAllSharedRecordsByStatusResponse> getSharedRecordByStatus() async {
    dynamic localRes;
    try {
      var request = GetAllSharedRecordsByStatusReq();
      // var result = await sharedPref.getObject(MAIN_USER);
      // request.status = 0;
      // request.patientID = result["PatientID"];
      await new BaseAppClient().post(GET_SHARED_RECORD_BY_STATUS, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request.toJson());

      sharedPref.setObject(FAMILY_FILE, localRes);
      return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(localRes));
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<GetAllSharedRecordsByStatusResponse> getUserViewRequest(responseID) async {
    try {
      dynamic localRes;
      Map<String, dynamic> request = {};
      request['ResponseID'] = responseID;
      await new BaseAppClient().post(RECEVIED_REQUEST_URL, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        return Future.error(error);
      }, body: request);
      if (localRes != null) {
        // sharedPref.setObject(FAMILY_FILE, localRes);
        allSharedRecordsByStatusResponse = GetAllSharedRecordsByStatusResponse.fromJson(localRes);
        return Future.value(allSharedRecordsByStatusResponse);
      } else
        return Future.error("No Data");
    } catch (error) {
      print("errorerror:$error");
      return Future.error(error);
    }
  }

  Future<GetAllSharedRecordsByStatusResponse> getUserSentRequest() async {
    try {
      dynamic localRes;
      Map<String, dynamic> request = {};
      request['Status'] = 0;
      await new BaseAppClient().post(SENT_REQUEST_URL, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        return Future.value(error);
        //AppToast.showErrorToast(message: error);
        //throw error;
      }, body: request);
      //sharedPref.setObject(FAMILY_FILE, localRes);
      return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(localRes));
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> addFamilyFile(AddFamilyFileReq request) async {
    try {
      dynamic localRes;
      // var request = GetAllSharedRecordsByStatusReq();
      //request.status = 0;
      await new BaseAppClient().post(ADD_FAMILY_FILES, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request.toJson());
      //sharedPref.setObject(FAMILY_FILE, localRes);
      return Future.value(localRes);
    } catch (error) {
      print(error);

      return Future.value(error);
    }
  }

  Future<dynamic> insertNewMember(InsertSharePatientFileReq request) async {
    try {
      dynamic localRes;
      // var request = GetAllSharedRecordsByStatusReq();
      //request.status = 0;
      await new BaseAppClient().post(INSERT_PATIENT_FILE, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        throw error;
      }, body: request.toJson());

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> sendActivationCode(cellNumber, zipCode, patientIdentificationID, responseID) async {
    try {
      dynamic localRes;
      var request = SendActivationRequest();
      request.zipCode = zipCode;
      request.patientMobileNumber = int.parse(cellNumber);
      request.patientIdentificationID = patientIdentificationID;
      request.projectOutSA = zipCode == '966' ? false : true;
      request.loginType = request.searchType = 1;
      request.oTPSendType = 1;
      request.isRegister = false;
      request.responseID = responseID;
      request.status = 2;
      request.familyRegionID = zipCode == '966' ? 1 : 2;
      await new BaseAppClient().post(SEND_FAMILY_FILE_ACTIVATION, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request.toJson());

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  //TODO
  Future<dynamic> checkActivationCode(loginTokenID, activationCode, indentification, mobileNo, requestID, responseID) async {
    try {
      dynamic localRes;
      Map<String, dynamic> request = {};
      // request['ZipCode'] = user.ZipCode;
      request['PatientMobileNumber'] = mobileNo;
      request['PatientIdentificationID'] = indentification;
      request['LogInTokenID'] = loginTokenID;
      request['activationCode'] = activationCode;
      request['PatientShareRequestID'] = requestID;
      request['ResponseID'] = responseID;
      request['Status'] = 3;

      // this.authService.authenticateRequest(request);
      await new BaseAppClient().post(CHECK_ACTIVATION_CODE, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> acceptAndRejectRecievedRequests(id, stauts) async {
    try {
      dynamic localRes;
      Map<String, dynamic> request = {};
      request['ID'] = id;
      request['Status'] = stauts;
      await new BaseAppClient().post(UPDATE_FILE_STATUS, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> deativateActivateMemberFile(request) async {
    try {
      dynamic localRes;

      await new BaseAppClient().post(REMOVE_FILE_STATUS, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> silentLoggin(GetAllSharedRecordsByStatusList switchUser, {onSuccess, mainUser}) async {
    Map<String, dynamic> request = {};
    if (mainUser == true) {
      var currentUser = AuthenticatedUser.fromJson(await sharedPref.getObject(MAIN_USER));

      request['PatientOutSA'] = currentUser.outSA; //currentUser.outSA; //? 1 : 0;
      request['LoginType'] = await sharedPref.getInt(LAST_LOGIN) ?? 1;
      request['MobileNo'] = currentUser.mobileNumber[0].toString() == "0" ? currentUser.mobileNumber.toString() : '0' + currentUser.mobileNumber.toString();
      request['PatientMobileNumber'] = currentUser.mobileNumber; //['MobileNumber'];
      request['SearchType'] = 2;
      // request['SuperUser'] = currentUser.patientID; //currentUser.PatientID;
      request['PatientIdentificationID'] = '';
      request['IsSilentLogin'] = true;
      request['DeviceToken'] = await sharedPref.getString(PUSH_TOKEN);
      request['PatientID'] = currentUser.patientID; //['PatientID'];
      request['ZipCode'] = currentUser.outSA == 1 ? "971" : "966";
      request['activationCode'] = '0000';
      request['isRegister'] = false;
    } else {
      var currentUser = AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
      //const request = new SwitchUserRequest();

      // request['LogInTokenID'] = '';
      // request['PatientOutSA'] = currentUser.outSA; //? 1 : 0;
      request['PatientOutSA'] = switchUser.familyRegionID != null ? switchUser.familyRegionID == 1 ? 0 : 1 : currentUser.outSA; //currentUser.outSA; //? 1 : 0;
      request['PatientMobileNumber'] = switchUser.mobileNumber; //['MobileNumber'];
      request['SearchType'] = 2;
      request['SuperUser'] = switchUser.patientID; //currentUser.PatientID;
      request['PatientIdentificationID'] = '';
      request['IsSilentLogin'] = true;
      request['PatientID'] = switchUser.responseID; //['PatientID'];
      request['ZipCode'] = switchUser.familyRegionID != null ? switchUser.familyRegionID == 1 ? "966" : "971" : "966";
      // request['ZipCode'] = currentUser.outSA == 1 ? "971" : "966";
      request['activationCode'] = '0000';
      request['isRegister'] = false;
    }
    try {
      dynamic localRes;

      await new BaseAppClient().post(ACTIVATION_CODE_URL, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);
      sharedPref.setString(BLOOD_TYPE, localRes['PatientBloodType']);
      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> acceptRejectFamily(request) async {
    try {
      dynamic localRes;

      await new BaseAppClient().post(ACCEPT_REJECT_FAMILY, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }

  Future<dynamic> deactivateFamily(request) async {
    try {
      dynamic localRes;

      await new BaseAppClient().post(DEACTIVATE_FAMILY, onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        throw error;
      }, body: request);

      return Future.value(localRes);
    } catch (error) {
      print(error);
      throw error;
    }
  }
}
