import 'dart:convert';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;

import '../../../routes.dart';

AppSharedPreferences sharedPref = new AppSharedPreferences();

///Example
///await BaseAppClient.post('',
///       onSuccess: (dynamic response, int statusCode) {},
///       onFailure: (String error, int statusCode) {},
///   body: null);

class BaseAppClient {
  post(String endPoint,
      {Map<String, dynamic> body,
      Function(dynamic response, int statusCode) onSuccess,
      Function(String error, int statusCode) onFailure,
      bool isAllowAny = false}) async {
    String url = BASE_URL + endPoint;
    try {
      //Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
      String token = await sharedPref.getString(TOKEN);
      var languageID =
          await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'en');
      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'] = DeviceTypeID;

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

        body['PatientTypeID'] = body.containsKey('PatientTypeID')
            ? body['PatientTypeID'] != null
            ? body['PatientTypeID']
            : 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'] = getSessionId(token);
        }
      }

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

      var asd="";
      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 {
          var parsed = json.decode(response.body.toString());
          if (parsed['Response_Message'] != null) {
            onSuccess(parsed, statusCode);
          } else {
            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 {
                onFailure(
                    parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                    statusCode);
                logout();
              }
            } else if (parsed['MessageStatus'] == 1 ||
                parsed['SMSLoginRequired'] == true) {
              onSuccess(parsed, statusCode);
            } else {
              if (parsed['SameClinicApptList'] != null) {
                onSuccess(parsed, statusCode);
              } else {
                onFailure(
                    parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                    statusCode);
              }
            }
          }
        }
      } else {
        onFailure('Please Check The Internet Connection', -1);
      }
    } catch (e) {
      print(e);
      onFailure(e.toString(), -1);
    }
  }

  logout() async {
    await sharedPref.remove(LOGIN_TOKEN_ID);
    Navigator.of(AppGlobal.context).pushReplacementNamed(LOGIN_TYPE);
  }

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