import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import '../dio_http_service/dio_http_service.dart';

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

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

  showLoading({int timeout = receiveTimeout}) {
    Future.delayed(Duration(seconds: timeout), () {
      hideLoading();
    });

    Future.delayed(Duration.zero, () {
      if (isShowLoading) return;
      isShowLoading = true;
      Get.dialog(
        Center(
          child: SizedBox(
            width: 40,
            height: 80,
            child: Stack(
              children: [
                CircularProgressIndicator(),
              ],
            ),
          ),
        ),
        barrierDismissible: false,
      );
    });
  }

  hideLoading() {
    if (isShowLoading) {
      isShowLoading = false;
      Get.back();
    }
  }

  showMessage(BuildContext context, String message) {
    fToast.init(context);
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.black.withValues(alpha: 0.8),
      ),
      child: Text(
        message,
        style: TextStyle(color: Colors.white),
      ),
    );
    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: Duration(seconds: 2),
    );
  }
}
