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");
    isLocationServiceEnabled().then((value) {
      if (value) {
        checkPermission().then((permission) {
          if (permission == LocationPermission.always ||
              permission == LocationPermission.whileInUse) {
            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)
                openAppSettings()
              else
                openLocationSettings()
            },
        cancelFunction: () => {});
    return dialog.showAlertDialog(context);
  }

  void setLocation(Position position) {
    print(position);
    this.sharedPref.setDouble(USER_LAT, position.latitude);
    this.sharedPref.setDouble(USER_LONG, position.longitude);
  }

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