import 'dart:io';

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/service/base_service.dart';
import 'package:hmg_patient_app/services/permission/permission_service.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class HospitalService extends BaseService {
  List<HospitalsModel> _hospitals =[];

  List<HospitalsModel> get hospitals => _hospitals;

  double? _latitude;
  double? _longitude;

  _getCurrentLocation() async {
    if (await PermissionService.isLocationEnabled()) {
      Geolocator.getLastKnownPosition().then((value) {
        _latitude = value!.latitude;
        _longitude = value.longitude;
      }).catchError((e) {
        _longitude = 0;
        _latitude = 0;
      });
    } else {
      if (Platform.isAndroid) {
        Utils.showPermissionConsentDialog(AppGlobal.context, TranslationBase.of(AppGlobal.context).locationPermissionDialog, () {
          Geolocator.getLastKnownPosition().then((value) {
            _latitude = value!.latitude;
            _longitude = value.longitude;
          }).catchError((e) {
            _longitude = 0;
            _latitude = 0;
          });
        });
      } else {
        Geolocator.getLastKnownPosition().then((value) {
          _latitude = value!.latitude;
          _longitude = value.longitude;
        }).catchError((e) {
          _longitude = 0;
          _latitude = 0;
        });
      }
    }
  }

  Future getHospitals(int languageID, {bool isResBasedOnLoc = true, bool isAdvancePayment = false}) async {
    if (isResBasedOnLoc) await _getCurrentLocation();
    Map<String, dynamic> body = Map();
    body['Latitude'] = await this.sharedPref.getDouble(USER_LAT);
    body['Longitude'] = await this.sharedPref.getDouble(USER_LONG);
    body['IsOnlineCheckIn'] = isResBasedOnLoc;
    body['IsAdvancePayment'] = isAdvancePayment;
    body['LanguageID'] = languageID;
    body['IsForER'] = true;

    await baseAppClient.post(GET_PROJECT, onSuccess: (dynamic response, int statusCode) {
      _hospitals.clear();
      response['ListProject'].forEach((hospital) {
        _hospitals.add(HospitalsModel.fromJson(hospital));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }
}
