import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'device_manager_model.dart';

class DeviceManagerViewModel extends RestfulApiViewModel {
  var logoutDevicesResponse = Rxn<DevicesLogoutListResponse>();
  var currentDevice = Rxn<DeviceItemModel>();
  void Function(String message)? onShowAlertError;

  getData() {
    getLogoutDevicesResponse();
    getCurrentDevice();
  }

  Future<void> getLogoutDevicesResponse() async {
    final body = {"page": 0, "limit": 200};
    showLoading();
    try {
      final response = await client.getLogoutDevices(body);
      hideLoading();
      if (response.isSuccess && response.data != null) {
        logoutDevicesResponse.value = response.data;
      } else {
        onShowAlertError?.call(response.message ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }

  Future<void> getCurrentDevice() async {
    final response = await client.getCurrentDevice();
    if (response.isSuccess && response.data != null) {
      currentDevice.value = response.data;
    }
  }

  Future<void> deleteDevice(DeviceItemModel item) async {
    if ((item.deviceKey ?? '').isEmpty) return;
    showLoading();
    try {
      final response = await client.deleteDevice(item.deviceKey ?? '');
      hideLoading();
      if (response.isSuccess) {
        getLogoutDevicesResponse();
        onShowAlertError?.call(response.data ?? "Đã xóa thiết bị thành công");
      } else {
        onShowAlertError?.call(response.message ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call("Error fetching product detail: $error");
    }
  }
}
