import 'dart:convert';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/medical/vital_sign_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/pages/appUpdatePage/app_update_page.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

import '../../../locator.dart';
import '../../../routes.dart';
import '../AuthenticatedUserObject.dart';
import 'dart:io' show Platform;

AppSharedPreferences sharedPref = new AppSharedPreferences();

///Example
///await BaseAppClient.post('',
///       onSuccess: (dynamic response, int statusCode) {},
///       onFailure: (String error, int statusCode) {},
///   body: Map();
///
AuthenticatedUserObject authenticatedUserObject =
    locator<AuthenticatedUserObject>();
VitalSignService _vitalSignService = locator<VitalSignService>();

class BaseAppClient {
  post(String endPoint,
      {Map<String, dynamic> body,
      Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      bool isAllowAny = false,
      bool isExternal = false}) async {
    String url;
    if (isExternal) {
      url = endPoint;
    } else {
      url = BASE_URL + endPoint;
    }
    try {
      //Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
      var pharmacyToken = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
      var user = await sharedPref.getObject(USER_PROFILE);
      Map<String, String> headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      };
      if (!isExternal) {
        String token = await sharedPref.getString(TOKEN);
        var languageID =
            await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
        if (body.containsKey('SetupID')) {
          body['SetupID'] = body.containsKey('SetupID')
              ? body['SetupID'] != null
                  ? body['SetupID']
                  : SETUP_ID
              : SETUP_ID;
        }

        body['VersionID'] = VERSION_ID;
        body['Channel'] = CHANNEL;
        body['LanguageID'] = (languageID == 'ar' ? 1 : 2);

        body['IPAdress'] = IP_ADDRESS;
        body['generalid'] = GENERAL_ID;

        if (body.containsKey('isDentalAllowedBackend')) {
          body['isDentalAllowedBackend'] =
              body.containsKey('isDentalAllowedBackend')
                  ? body['isDentalAllowedBackend'] != null
                      ? body['isDentalAllowedBackend']
                      : IS_DENTAL_ALLOWED_BACKEND
                  : IS_DENTAL_ALLOWED_BACKEND;
        }

        body['DeviceTypeID'] = Platform.isAndroid ? 1 : 2;

        if (!body.containsKey('IsPublicRequest')) {
          body['PatientType'] = body.containsKey('PatientType')
              ? body['PatientType'] != null
                  ? body['PatientType']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE
              : PATIENT_TYPE;

          body['PatientTypeID'] = body.containsKey('PatientTypeID')
              ? body['PatientTypeID'] != null
                  ? body['PatientTypeID']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE_ID
              : PATIENT_TYPE_ID;
          if (user != null) {
            body['TokenID'] = token;
            body['PatientID'] = body['PatientID'] != null
                ? body['PatientID']
                : user['PatientID'];
            body['PatientOutSA'] = user['OutSA'];
            body['PatientOutSA'] = body.containsKey('PatientOutSA')
                ? body['PatientOutSA'] != null
                    ? body['PatientOutSA']
                    : PATIENT_OUT_SA
                : PATIENT_OUT_SA;
            body['SessionID'] = SESSION_ID; //getSe

            headers = {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'Authorization': pharmacyToken,
              'Mobilenumber': user != null
                  ? Utils.getPhoneNumberWithoutZero(
                      user['MobileNumber'].toString())
                  : "",
              'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
              'Username': user['PatientID'].toString(),
            };
          }
        }
      }

      print("URL : $url");
      final jsonBody = json.encode(body);
      print(jsonBody);

      if (await Utils.checkConnection()) {
        final response = await http.post(url.trim(),
            body: json.encode(body), headers: headers);
        final int statusCode = response.statusCode;
        print("statusCode :$statusCode");
        if (statusCode < 200 || statusCode >= 400 || json == null) {
          onFailure('Error While Fetching data', statusCode);
        } else {
          // var parsed = json.decode(response.body.toString());
          var parsed = json.decode(utf8.decode(response.bodyBytes));
          if (parsed['Response_Message'] != null) {
            onSuccess(parsed, statusCode);
          } else {
            if (parsed['ErrorType'] == 4) {
              navigateToAppUpdate(
                  AppGlobal.context, parsed['ErrorEndUserMessage']);
            }
            if (isAllowAny) {
              onSuccess(parsed, statusCode);
            } else if (parsed['IsAuthenticated'] == null) {
              if (parsed['isSMSSent'] == true) {
                onSuccess(parsed, statusCode);
              } else if (parsed['MessageStatus'] == 1) {
                onSuccess(parsed, statusCode);
              } else if (parsed['Result'] == 'OK') {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed != null) {
                  onSuccess(parsed, statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                  logout();
                }
              }
            } else if (parsed['MessageStatus'] == 1 ||
                parsed['SMSLoginRequired'] == true) {
              onSuccess(parsed, statusCode);
            } else if (parsed['MessageStatus'] == 2 &&
                parsed['IsAuthenticated']) {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed['message'] == null &&
                    parsed['ErrorEndUserMessage'] == null) {
                  if (parsed['ErrorSearchMsg'] == null) {
                    onFailure("Server Error found with no available message",
                        statusCode);
                  } else {
                    onFailure(parsed['ErrorSearchMsg'], statusCode);
                  }
                } else {
                  onFailure(
                      parsed['message'] ??
                          parsed['ErrorEndUserMessage'] ??
                          parsed['ErrorMessage'],
                      statusCode);
                }
              }
            } else if (!parsed['IsAuthenticated']) {
              await logout();

              //helpers.showErrorToast('Your session expired Please login agian');
            } else {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed['message'] != null) {
                  onFailure(parsed['message'] ?? parsed['message'], statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                }
              }
            }
          }
        }
      } else {
        onFailure('Please Check The Internet Connection', -1);
      }
    } catch (e) {
      print(e);
      onFailure(e.toString(), -1);
    }
  }

  postPharmacy(String endPoint,
      {Map<String, dynamic> body,
      Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      bool isAllowAny = false,
      bool isExternal = false}) async {
    var token = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
    var user = await sharedPref.getObject(USER_PROFILE);
    String url;
    if (isExternal) {
      url = endPoint;
    } else {
      url = PHARMACY_BASE_URL + endPoint;
    }
    try {
      //Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
      var pharmacyToken = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
      var user = await sharedPref.getObject(USER_PROFILE);
      Map<String, String> headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': token ?? '',
        'Mobilenumber': user != null
            ? Utils.getPhoneNumberWithoutZero(user['MobileNumber'].toString())
            : "",
        'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        'Username': user != null ? user['PatientID'].toString() : "",
      };
      if (!isExternal) {
        String token = await sharedPref.getString(TOKEN);
        var languageID =
            await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
        if (body.containsKey('SetupID')) {
          body['SetupID'] = body.containsKey('SetupID')
              ? body['SetupID'] != null
                  ? body['SetupID']
                  : SETUP_ID
              : SETUP_ID;
        }

        body['VersionID'] = VERSION_ID;
        body['Channel'] = CHANNEL;
        body['LanguageID'] = languageID == 'ar' ? 1 : 2;

        body['IPAdress'] = IP_ADDRESS;
        body['generalid'] = GENERAL_ID;
        body['PatientOutSA'] = body.containsKey('PatientOutSA')
            ? body['PatientOutSA'] != null
                ? body['PatientOutSA']
                : PATIENT_OUT_SA
            : PATIENT_OUT_SA;

        if (body.containsKey('isDentalAllowedBackend')) {
          body['isDentalAllowedBackend'] =
              body.containsKey('isDentalAllowedBackend')
                  ? body['isDentalAllowedBackend'] != null
                      ? body['isDentalAllowedBackend']
                      : IS_DENTAL_ALLOWED_BACKEND
                  : IS_DENTAL_ALLOWED_BACKEND;
        }

        body['DeviceTypeID'] = Platform.isAndroid ? 1 : 2;

        if (!body.containsKey('IsPublicRequest')) {
          body['PatientType'] = body.containsKey('PatientType')
              ? body['PatientType'] != null
                  ? body['PatientType']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE
              : PATIENT_TYPE;

          body['PatientTypeID'] = body.containsKey('PatientTypeID')
              ? body['PatientTypeID'] != null
                  ? body['PatientTypeID']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE_ID
              : PATIENT_TYPE_ID;
          if (user != null) {
            body['TokenID'] = token;
            body['PatientID'] = body['PatientID'] != null
                ? body['PatientID']
                : user['PatientID'];
            body['PatientOutSA'] = user['OutSA'];
            body['SessionID'] = SESSION_ID; //getSe
            headers = {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'Authorization': pharmacyToken,
              'Mobilenumber': user['MobileNumber'].toString(),
              'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
              'Username': user['PatientID'].toString(),
            };
          }
        }
      }

      print("URL : $url");
      print("Body : ${json.encode(body)}");

      if (await Utils.checkConnection()) {
        final response = await http.post(url.trim(),
            body: json.encode(body), headers: headers);
        final int statusCode = response.statusCode;
        print("statusCode :$statusCode");
        if (statusCode < 200 || statusCode >= 400 || json == null) {
          onFailure('Error While Fetching data', statusCode);
        } else {
          // var parsed = json.decode(response.body.toString());
          var parsed = json.decode(utf8.decode(response.bodyBytes));
          if (parsed['Response_Message'] != null) {
            onSuccess(parsed, statusCode);
          } else {
            if (parsed['ErrorType'] == 4) {
              navigateToAppUpdate(
                  AppGlobal.context, parsed['ErrorEndUserMessage']);
            }
            if (isAllowAny) {
              onSuccess(parsed, statusCode);
            } else if (parsed['IsAuthenticated'] == null) {
              if (parsed['isSMSSent'] == true) {
                onSuccess(parsed, statusCode);
              } else if (parsed['MessageStatus'] == 1) {
                onSuccess(parsed, statusCode);
              } else if (parsed['Result'] == 'OK') {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed != null) {
                  onSuccess(parsed, statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                  logout();
                }
              }
            } else if (parsed['MessageStatus'] == 1 ||
                parsed['SMSLoginRequired'] == true) {
              onSuccess(parsed, statusCode);
            } else if (parsed['MessageStatus'] == 2 &&
                parsed['IsAuthenticated']) {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed['message'] == null &&
                    parsed['ErrorEndUserMessage'] == null) {
                  if (parsed['ErrorSearchMsg'] == null) {
                    onFailure("Server Error found with no available message",
                        statusCode);
                  } else {
                    onFailure(parsed['ErrorSearchMsg'], statusCode);
                  }
                } else {
                  onFailure(
                      parsed['message'] ??
                          parsed['ErrorEndUserMessage'] ??
                          parsed['ErrorMessage'],
                      statusCode);
                }
              }
            } else if (!parsed['IsAuthenticated']) {
              await logout();

              //helpers.showErrorToast('Your session expired Please login agian');
            } else {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed['message'] != null) {
                  onFailure(parsed['message'] ?? parsed['message'], statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                }
              }
            }
          }
        }
      } else {
        onFailure('Please Check The Internet Connection', -1);
      }
    } catch (e) {
      print(e);
      onFailure(e.toString(), -1);
    }
  }

  Future navigateToAppUpdate(context, String text) async {
    Navigator.pushReplacement(
        context, FadePage(page: AppUpdatePage(appUpdateText: text)));
  }

  get(String endPoint,
      {Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      Map<String, dynamic> queryParams,
      bool isExternal = false}) async {
    String url;
    if (isExternal) {
      url = endPoint;
    } else {
      url = BASE_URL + endPoint;
    }
    if (queryParams != null) {
      String queryString = Uri(queryParameters: queryParams).query;
      url += '?' + queryString;
    }

    print("URL : $url");

    if (await Utils.checkConnection()) {
      final response = await http.get(
        url.trim(),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      );
      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        onFailure('Error While Fetching data', statusCode);
      } else {
        // var parsed = json.decode(response.body.toString());
        var parsed = json.decode(utf8.decode(response.bodyBytes));
        onSuccess(parsed, statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  getPharmacy(String endPoint,
      {Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      bool isAllowAny = false,
      bool isExternal = false,
      Map<String, dynamic> queryParams}) async {
    var token = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
    var user = await sharedPref.getObject(USER_PROFILE);

    String url;
    if (isExternal) {
      url = endPoint;
    } else {
      url = PHARMACY_BASE_URL + endPoint;
    }
    if (queryParams != null) {
      String queryString = Uri(queryParameters: queryParams).query;
      url += '?' + queryString;
    }

    print("URL : $url");

    if (await Utils.checkConnection()) {
      final response = await http.get(url.trim(), headers: {
        'Content-Type': 'text/html; charset=utf-8',
        'Accept': 'application/json',
        'Authorization': token ?? '',
        'Mobilenumber': user != null
            ? Utils.getPhoneNumberWithoutZero(user['MobileNumber'].toString())
            : "",
        'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        'Username': user != null ? user['PatientID'].toString() : "",
        'Host': "mdlaboratories.com",
      });
      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        if (statusCode == 401) {
          AppToast.showErrorToast(
              message: TranslationBase.of(AppGlobal.context).pharmacyRelogin);
          Navigator.of(AppGlobal.context).pushNamed(HOME);
        } else {
          onFailure('Error While Fetching data', statusCode);
        }
      } else {
        // var parsed = json.decode(response.body.toString());
        var bodyUtf = json.decode(utf8.decode(response.bodyBytes));
        onSuccess(bodyUtf, statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  simplePost(
    String fullUrl, {
    Map<String, dynamic> body,
    Function(dynamic response, int statusCode) onSuccess,
    Function(String error, int statusCode) onFailure,
  }) async {
    String url = fullUrl;
    print("URL Query String: $url");

    if (await Utils.checkConnection()) {
      final response = await http.post(
        url.trim(),
        body: json.encode(body),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      );

      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        onFailure('Error While Fetching data', statusCode);
      } else {
        onSuccess(response.body.toString(), statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  simpleGet(String fullUrl,
      {Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      Map<String, String> queryParams}) async {
    String url = fullUrl;
    print("URL Query String: $url");

    var haveParams = (queryParams != null);
    if (haveParams) {
      String queryString = Uri(queryParameters: queryParams).query;
      url += '?' + queryString;
      print("URL Query String: $url");
    }

    if (await Utils.checkConnection()) {
      final response = await http.get(
        url.trim(),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      );

      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        onFailure('Error While Fetching data', statusCode);
      } else {
        onSuccess(response.body.toString(), statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  simplePut(String fullUrl,
      {Map<String, dynamic> body,
      Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure}) async {
    String url = fullUrl;
    print("URL Query String: $url");

    if (await Utils.checkConnection()) {
      final response = await http.put(
        url.trim(),
        body: json.encode(body),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      );

      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        onFailure('Error While Fetching data', statusCode);
      } else {
        onSuccess(response.body.toString(), statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  simpleDelete(String fullUrl,
      {Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      Map<String, String> queryParams}) async {
    String url = fullUrl;
    print("URL Query String: $url");

    var haveParams = (queryParams != null);
    if (haveParams) {
      String queryString = Uri(queryParameters: queryParams).query;
      url += '?' + queryString;
      print("URL Query String: $url");
    }

    if (await Utils.checkConnection()) {
      final response = await http.delete(
        url.trim(),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      );

      final int statusCode = response.statusCode;
      print("statusCode :$statusCode");

      if (statusCode < 200 || statusCode >= 400 || json == null) {
        onFailure('Error While Fetching data', statusCode);
      } else {
        onSuccess(response.body.toString(), statusCode);
      }
    } else {
      onFailure('Please Check The Internet Connection', -1);
    }
  }

  logout() async {
    await sharedPref.remove(LOGIN_TOKEN_ID);
    await sharedPref.remove(PHARMACY_CUSTOMER_ID);
    await authenticatedUserObject.getUser();
    Provider.of<ProjectViewModel>(AppGlobal.context, listen: false).isLogin =
        false;
    var model =
        Provider.of<ToDoCountProviderModel>(AppGlobal.context, listen: false);
    _vitalSignService.weightKg = "";
    _vitalSignService.heightCm = "";
    model.setState(0, false);
    Navigator.of(AppGlobal.context).pushReplacementNamed(HOME);
  }

  String getSessionId(String id) {
    ///return id.replaceAll(RegExp('/[^\w\s]/'), '');
    return id.replaceAll(RegExp('/[^a-zA-Z ]'), '');
  }

  static defaultHttpParameters() async {
    String token = await sharedPref.getString(TOKEN);
    var languageID =
        await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
    var user = await sharedPref.getObject(USER_PROFILE);
    var params = {};
    if (user != null) {
      params['TokenID'] = token;
      params['PatientID'] = user['PatientID'];
      params['PatientOutSA'] = user['OutSA'];
      params['SessionID'] = SESSION_ID; //getSessionId(token);
    }

    params['IPAdress'] = IP_ADDRESS;
    params['generalid'] = GENERAL_ID;
    params['VersionID'] = VERSION_ID;
    params['Channel'] = CHANNEL;
    params['LanguageID'] = languageID == 'ar' ? 1 : 2;

    return params;
  }

  pharmacyPost(String endPoint,
      {Map<String, dynamic> body,
      Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      bool isAllowAny = false,
      bool isExternal = false}) async {
    var token = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
    var user = await sharedPref.getObject(USER_PROFILE);
    String url;
    if (isExternal) {
      url = endPoint;
    } else {
      url = BASE_PHARMACY_URL + endPoint;
    }
    try {
      if (isExternal) {
        String token = await sharedPref.getString(TOKEN);
        var languageID =
            await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
        var user = await sharedPref.getObject(USER_PROFILE);
        if (body.containsKey('SetupID')) {
          body['SetupID'] = body.containsKey('SetupID')
              ? body['SetupID'] != null
                  ? body['SetupID']
                  : SETUP_ID
              : SETUP_ID;
        }

        body['VersionID'] = VERSION_ID;
        body['Channel'] = CHANNEL;
        body['LanguageID'] = languageID == 'ar' ? 1 : 2;

        body['IPAdress'] = IP_ADDRESS;
        body['generalid'] = GENERAL_ID;
        body['PatientOutSA'] = body.containsKey('PatientOutSA')
            ? body['PatientOutSA'] != null
                ? body['PatientOutSA']
                : PATIENT_OUT_SA
            : PATIENT_OUT_SA;

        if (body.containsKey('isDentalAllowedBackend')) {
          body['isDentalAllowedBackend'] =
              body.containsKey('isDentalAllowedBackend')
                  ? body['isDentalAllowedBackend'] != null
                      ? body['isDentalAllowedBackend']
                      : IS_DENTAL_ALLOWED_BACKEND
                  : IS_DENTAL_ALLOWED_BACKEND;
        }

        body['DeviceTypeID'] = Platform.isAndroid ? 1 : 2;

        if (!body.containsKey('IsPublicRequest')) {
          body['PatientType'] = body.containsKey('PatientType')
              ? body['PatientType'] != null
                  ? body['PatientType']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE
              : PATIENT_TYPE;

          body['PatientTypeID'] = body.containsKey('PatientTypeID')
              ? body['PatientTypeID'] != null
                  ? body['PatientTypeID']
                  : user['PatientType'] != null
                      ? user['PatientType']
                      : PATIENT_TYPE_ID
              : PATIENT_TYPE_ID;
          if (user != null) {
            body['TokenID'] = token;
            body['PatientID'] = body['PatientID'] != null
                ? body['PatientID']
                : user['PatientID'];
            body['PatientOutSA'] = user['OutSA'];
            body['SessionID'] = SESSION_ID; //getSessionId(token);
          }
        }
      }

      print("URL : $url");
      print("Body : ${json.encode(body)}");
      var ss = json.encode(body);

      if (await Utils.checkConnection()) {
        final response =
            await http.post(url.trim(), body: json.encode(body), headers: {
          // 'Content-Type': 'application/json',
          // 'Accept': 'application/json',
          // 'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': token ?? '',
          'Mobilenumber': user != null
              ? Utils.getPhoneNumberWithoutZero(user['MobileNumber'].toString())
              : "",
          'Statictoken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
          'Username': user != null ? user['PatientID'].toString() : "",
        });
        final int statusCode = response.statusCode;
        print("statusCode :$statusCode");
        if (statusCode < 200 || statusCode >= 400 || json == null) {
          onFailure('Error While Fetching data', statusCode);
        } else {
          // var parsed = json.decode(response.body.toString());
          var parsed = json.decode(utf8.decode(response.bodyBytes));
          if (parsed['Response_Message'] != null) {
            onSuccess(parsed, statusCode);
          } else {
            if (parsed['ErrorType'] == 4) {
              navigateToAppUpdate(
                  AppGlobal.context, parsed['ErrorEndUserMessage']);
            }
            if (isAllowAny) {
              onSuccess(parsed, statusCode);
            } else if (parsed['IsAuthenticated'] == null) {
              if (parsed['isSMSSent'] == true) {
                onSuccess(parsed, statusCode);
              } else if (parsed['MessageStatus'] == 1) {
                onSuccess(parsed, statusCode);
              } else if (parsed['Result'] == 'OK') {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed != null) {
                  onSuccess(parsed, statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                  logout();
                }
              }
            } else if (parsed['MessageStatus'] == 1 ||
                parsed['SMSLoginRequired'] == true) {
              onSuccess(parsed, statusCode);
            } else if (parsed['MessageStatus'] == 2 &&
                parsed['IsAuthenticated']) {
              if (parsed['message'] == null &&
                  parsed['ErrorEndUserMessage'] == null) {
                if (parsed['ErrorSearchMsg'] == null) {
                  onFailure("Server Error found with no available message",
                      statusCode);
                } else {
                  onFailure(parsed['ErrorSearchMsg'], statusCode);
                }
              } else {
                onFailure(
                    parsed['message'] ??
                        parsed['ErrorEndUserMessage'] ??
                        parsed['ErrorMessage'],
                    statusCode);
              }
            } else if (!parsed['IsAuthenticated']) {
              await logout();

              //helpers.showErrorToast('Your session expired Please login agian');
            } else {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                if (parsed['message'] != null) {
                  onFailure(parsed['message'] ?? parsed['message'], statusCode);
                } else {
                  onFailure(
                      parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                      statusCode);
                }
              }
            }
          }
        }
      } else {
        onFailure('Please Check The Internet Connection', -1);
      }
    } catch (e) {
      print(e);
      onFailure(e.toString(), -1);
    }
  }
}
