import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_inspection/presentation/action/view.dart';
import 'package:rasadyar_inspection/presentation/filter/view.dart';
import 'package:rasadyar_inspection/presentation/profile/view.dart';

enum ErrorLocationType { serviceDisabled, permissionDenied, none }

class RootLogic extends GetxController {
  RxInt currentIndex = 0.obs;
  List<Widget> pages = [SupervisionFilterPage(), ActionPage(), ProfilePage()];
  RxList<ErrorLocationType> errorLocationType = RxList();

  Stream<bool> listenToLocationServiceStatus() {
    return Geolocator.getServiceStatusStream().map((status) {
      return status == ServiceStatus.enabled;
    });
  }

  Future<bool> locationServiceEnabled() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return false;
    }
    return true;
  }

  Future<bool> checkPermission({bool request = false}) async {
    try {
      final LocationPermission permission = await Geolocator.checkPermission();

      switch (permission) {
        case LocationPermission.denied:
          final LocationPermission requestResult = await Geolocator.requestPermission();
          return requestResult != LocationPermission.denied &&
              requestResult != LocationPermission.deniedForever;

        case LocationPermission.deniedForever:

          return request ? await Geolocator.openAppSettings() : false;

        case LocationPermission.always:
        case LocationPermission.whileInUse:

          return true;

        default:
          return false;
      }
    } catch (e) {

      eLog(e);
      return await Geolocator.openLocationSettings();
    }
  }

  @override
  void onReady() {
    super.onReady();

    locationServiceEnabled().then((value) {
      if (!value) {
        errorLocationType.add(ErrorLocationType.serviceDisabled);
      }
    });

    checkPermission().then((value) {
      if (!value) {
        errorLocationType.add(ErrorLocationType.permissionDenied);
      }
    });

    listenToLocationServiceStatus().listen((event) {
      if (!event) {
        errorLocationType.add(ErrorLocationType.serviceDisabled);
      } else {
        errorLocationType.remove(ErrorLocationType.serviceDisabled);
      }
    });
  }

  void changePage(int index) {
    currentIndex.value = index;
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }
}
