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 {
  final Rxn<DevicesLogoutListResponse> logoutDevicesResponse = Rxn<DevicesLogoutListResponse>();
  final Rxn<DeviceItemModel> currentDevice = Rxn<DeviceItemModel>();
  void Function(String message)? onShowAlertError;

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

  Future<void> getLogoutDevicesResponse() async {
    final body = {"page": 0, "limit": 200};
    await callApi<DevicesLogoutListResponse>(
      request: () => client.getLogoutDevices(body),
      onSuccess: (data, _) {
        logoutDevicesResponse.value = data;
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  Future<void> getCurrentDevice() async {
    await callApi<DeviceItemModel>(
      request: () => client.getCurrentDevice(),
      onSuccess: (data, _) {
        currentDevice.value = data;
      },
      onFailure: (_, _, _) async {},
      withLoading: false,
    );
  }

  Future<void> deleteDevice(DeviceItemModel item) async {
    final key = item.deviceKey ?? '';
    if (key.isEmpty) return;
    await callApi<String>(
      request: () => client.deleteDevice(key),
      onSuccess: (data, _) async {
        await getLogoutDevicesResponse();
        onShowAlertError?.call(data);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }
}
