import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/shared/widgets/loading/app_loading.dart';

class BaseViewModel extends GetxController with WidgetsBindingObserver {
  var isShowLoading = false;
  RxBool isShowKey = false.obs;
  FToast fToast = FToast();
  final RxBool isLoading = false.obs;
  int _trackedLoadingCount = 0;

  @override
  void onInit() {
    super.onInit();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    final bottomInset = WidgetsBinding.instance.platformDispatcher.views.first.viewInsets.bottom;
    final newValue = bottomInset > 0.0;
    if (newValue != isShowKey.value) {
      isShowKey.value = newValue;
    }
  }

  void showLoading() {
    AppLoading().show();
  }

  void hideLoading() {
    AppLoading().hide();
  }

  @protected
  void beginTrackedLoading() {
    _trackedLoadingCount++;
    if (_trackedLoadingCount >= 1) {
      isLoading.value = true;
    }
  }

  @protected
  void endTrackedLoading() {
    // if (_trackedLoadingCount == 0) return;
    _trackedLoadingCount--;
    if (_trackedLoadingCount <= 0) {
      isLoading.value = false;
    }
  }
}
