import 'dart:convert';

import 'package:driverapp/config/config.dart';
import 'package:driverapp/config/shared_pref_kay.dart';
import 'package:driverapp/core/model/authentication/authenticated_user.dart';
import 'package:driverapp/uitl/app_shared_preferences.dart';
import 'package:driverapp/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 {
  String  _Statictoken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
  post(
      String endPoint, {
        Map<String, dynamic> body,
        Function(dynamic response, int statusCode) onSuccess,
        Function(String error, int statusCode) onFailure}) async {
    String url = BASE_URL + endPoint;
    try {
      Map profile = await sharedPref.getObject(USER_PROFILE);
      String token = await sharedPref.getString(TOKEN);
      if (profile != null) {
        AuthenticatedUser doctorProfile = AuthenticatedUser.fromJson(profile);
        if(!body.keys.contains('DriverID') || body['DriverID'] == null)
          body['DriverID'] = doctorProfile?.userID;
        if(!body.keys.contains('UserID') || body['UserID'] == null)
          body['UserID'] = '${doctorProfile?.userID}';
        body['CreatedBy'] = doctorProfile?.userID;
        body['TokenID'] = token;
        body['MobileNo'] = doctorProfile?.mobileNumber;
      }
      body['Channel'] = CHANNEL;
      body['VersionID'] = VERSION_ID;

      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',
              'Statictoken': _Statictoken
            });
        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 (!parsed['IsAuthenticated']) {
            // await helpers.logout();
            //helpers.showErrorToast('Your session expired Please login agian');
            // TODO create logout fun
            onFailure("Unauthorized", 401);
          } else if (parsed['MessageStatus'] == 1) {
            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);
    }
  }

  get(
      String endPoint, {
        Map<String, dynamic> body,
        Function(dynamic response, int statusCode) onSuccess,
        Function(String error, int statusCode) onFailure}) async {
    String url = BASE_URL + endPoint;
    try {
      if (await Utils.checkConnection()) {
        final response = await http.get(url,
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'Statictoken': _Statictoken
            });
        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 (parsed['MessageStatus'] == 1) {
            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);
    }
  }


  simpleGet(
      String url,
      { Function(dynamic response, int statusCode) onSuccess,
        Function(String error, int statusCode) onFailure}) async {
    try {
      if (await Utils.checkConnection()) {
        final response = await http.get(url,
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'Statictoken': _Statictoken
            });
        final int statusCode = response.statusCode;
        if (statusCode < 200 || statusCode >= 400) {
          onFailure('Error While Fetching data', statusCode);
        } else {
          onSuccess(response.body, statusCode);
        }
      } else {
        onFailure('Please Check The Internet Connection', -1);
      }
    } catch (e) {
      print(e);
      onFailure(e.toString(), -1);
    }
  }
}
