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:http/http.dart' as http;

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);

      body['SetupID'] = SETUP_ID;
      body['VersionID'] = VERSION_ID;
      body['Channel'] = CHANNEL;
      body['LanguageID'] = LANGUAGE;
      body['IPAdress'] = IP_ADDRESS;
      body['generalid'] = GENERAL_ID;
      body['PatientOutSA'] = PATIENT_OUT_SA;
      body['SessionID'] = SESSION_ID;
      body['isDentalAllowedBackend'] = IS_DENTAL_ALLOWED_BACKEND;
      body['DeviceTypeID'] = DeviceTypeID;
      body['PatientType'] = PATIENT_TYPE;
      body['PatientTypeID'] = PATIENT_TYPE_ID;
      body['TokenID'] = '@dm!n';
      body['PatientID'] = 1231755;

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

      if (await Utils.checkConnection()) {
        final response = await http.post(url,
            body: json.encode(body),
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            });
        final int statusCode = response.statusCode;
        if (statusCode < 200 || statusCode >= 400 || json == null) {
          onFailure('Error While Fetching data', statusCode);
        } else {
          var parsed = json.decode(response.body.toString());
          if (isAllowAny) {
            onSuccess(parsed, statusCode);
          } else if (!parsed['IsAuthenticated']) {
            if (parsed['isSMSSent'] == true) {
              onSuccess(parsed, statusCode);
            } else if (parsed['MessageStatus'] == 1) {
              onSuccess(parsed, statusCode);
            } else {
              onFailure(parsed['ErrorEndUserMessage'] ?? parsed['ErrorMessage'],
                  statusCode);
              logout();
            }

          } else if (parsed['MessageStatus'] == 1 ||
              parsed['SMSLoginRequired'] == true) {
            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);
  }
}
