import 'package:get/get.dart';

import '../../data/models/site_settings_properties_model.dart';
import '../../data/repositories/site_settings_properties_repository.dart';
import '../services/currency_service.dart';

class CurrencyController extends GetxController {
  final SiteSettingsPropertiesRepository repo;
  final CurrencyService service;
  CurrencyController(this.repo, this.service);

  final currencies = <CurrencyModel>[].obs;

  final Rx<CurrencyModel?> selectedRx = Rx<CurrencyModel?>(null);

  final isLoading = false.obs;
  final error = RxnString();

  CurrencyModel? get selected => selectedRx.value;

  @override
  void onInit() {
    super.onInit();
    fetchCurrencies();
  }

  Future<void> fetchCurrencies() async {
    isLoading.value = true;
    error.value = null;
    try {
      final list = await repo.fetchCurrencies();
      currencies.assignAll(list);

      if (service.current == null) {
        service.restoreFrom(list);
      }

      selectedRx.value = service.current;
    } catch (e) {
      error.value = e.toString();
    } finally {
      isLoading.value = false;
    }
  }

  void select(CurrencyModel c) {
    service.setCurrency(c);
    selectedRx.value = c;
    update();
  }

  String format(num amount, {bool applyConversion = true}) {
    final cur = selectedRx.value ?? service.current;
    if (cur == null) {
      return amount.toStringAsFixed(2);
    }
    return service.format(amount.toDouble(), applyConversion: applyConversion);
  }

  void refreshSelected() {
    selectedRx.value = service.current;
    update();
  }
}
