import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:geolocator/geolocator.dart';

class LocationUtils {
  AppSharedPreferences sharedPref = new AppSharedPreferences();

  bool isShowConfirmDialog;
  BuildContext context;

  LocationUtils({@required this.isShowConfirmDialog, @required this.context});

  void getCurrentLocation() async {
    print("current location");
    Geolocator.isLocationServiceEnabled().then((value) {
      if (value) {
        Geolocator.checkPermission().then((permission) {
          if (permission == LocationPermission.always ||
              permission == LocationPermission.whileInUse) {
            Geolocator.getLastKnownPosition()
                .then((value) => setLocation(value));
          }

          if (permission == LocationPermission.denied ||
              permission == LocationPermission.deniedForever) {
            setZeroLocation();
            if (isShowConfirmDialog) showErrorLocationDialog(false);
          }
        }).catchError((err) {
          print(err);
        });
      } else {
        if (isShowConfirmDialog) showErrorLocationDialog(false);
      }
    }).catchError((err) {
      print(err);
    });
  }

  showErrorLocationDialog(bool isPermissionError) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).locationDialogMessage,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () => {
              ConfirmDialog.closeAlertDialog(context),
              if (isPermissionError)
                Geolocator.openAppSettings()
              else
                Geolocator.openLocationSettings()
            },
        cancelFunction: () => {});
    return dialog.showAlertDialog(context);
  }

  void setLocation(Position position) {
    this
        .sharedPref
        .setDouble(USER_LAT, position != null ? position.latitude : 0.0);
    this
        .sharedPref
        .setDouble(USER_LONG, position != null ? position.longitude : 0.0);
  }

  void setZeroLocation() {
    this.sharedPref.setDouble(USER_LAT, 0.0);
    this.sharedPref.setDouble(USER_LONG, 0.0);
  }
}
