import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_inspection/data/model/response/user_profile/user_profile_model.dart';
import 'package:rasadyar_inspection/data/repositories/user/user_repository_imp.dart';
import 'package:rasadyar_inspection/injection/inspection_di.dart';
import 'package:rasadyar_inspection/presentation/pages/action/view.dart';
import 'package:rasadyar_inspection/presentation/pages/inspection_map/view.dart';
import 'package:rasadyar_inspection/presentation/pages/profile/view.dart';

enum ErrorLocationType { serviceDisabled, permissionDenied, none }

class RootLogic extends GetxController {
  RxInt currentIndex = 0.obs;
  List<Widget> pages = [InspectionMapPage(), ActionPage(), ProfilePage()];
  RxList<ErrorLocationType> errorLocationType = RxList();
  TokenStorageService tokenStorageService = Get.find<TokenStorageService>();
  UserRepositoryImp userRepository = diInspection.get<UserRepositoryImp>();
  Rxn<UserProfileModel> userProfile = Rxn<UserProfileModel>();

  @override
  void onInit() {
    super.onInit();
    userRepository
        .fetchUserProfile(token: tokenStorageService.accessToken.value ?? '')
        .then((value) => userProfile.value = value);
  }

  @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);
      }
    });
  }

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

  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();
    }
  }

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