import 'dart:convert';

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/providers/project_provider.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
Helpers helpers = new Helpers();
//ProjectProvider projectsProvider = new ProjectProvider();

/*
 *@author: Mohammad Aljammal
 *@Date:28/5/2020
 *@param: url, onSuccess callBack, onFailure callBack
 *@return:
 *@desc:
 */

///Example
/*
 await BaseAppClient.post('',
        onSuccess: (dynamic response, int statusCode) {},
        onFailure: (String error, int statusCode) {},
    body: null);
* */
class BaseAppClient {
  static 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.getObj(DOCTOR_PROFILE);
      String token = await sharedPref.getString(TOKEN);
      if (profile != null) {
        DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);

        body['DoctorID'] = doctorProfile?.doctorID;
        body['EditedBy'] = doctorProfile?.doctorID;
        body['ProjectID'] = doctorProfile?.projectID;
        if (body['ClinicID'] == null)
          body['ClinicID'] = doctorProfile?.clinicID;
      }
      body['TokenID'] = token ?? '';

      String lang = await sharedPref.getString(APP_Language);
      if (lang != null && lang == 'ar')
        body['LanguageID'] = 1;
      else
        body['LanguageID'] = 2;

      body['stamp'] = STAMP;
      body['IPAdress'] = IP_ADDRESS;
      body['VersionID'] = VERSION_ID;
      if (body['Channel'] == null) body['Channel'] = CHANNEL;
      body['SessionID'] = SESSION_ID;
      body['IsLoginForDoctorApp'] = IS_LOGIN_FOR_DOCTOR_APP;
      body['PatientOutSA'] = 0; // PATIENT_OUT_SA;
      print("URL : $url");
      print("Body : ${json.encode(body)}");

      if (await Helpers.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 (!parsed['IsAuthenticated']) {
            await helpers.logout();

            helpers.showErrorToast('Your session expired Please login agian');
          } 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);
    }
  }
}
