import 'package:flutter/foundation.dart';

import 'package:pshared/models/payment/operation.dart';
import 'package:pshared/provider/payment/payments.dart';

import 'package:pweb/utils/report/operations/operations.dart';
import 'package:pweb/utils/report/payment_mapper.dart';


class RecentPaymentsController extends ChangeNotifier {
  PaymentsProvider? _payments;
  List<OperationItem> _recent = const [];

  List<OperationItem> get recentOperations => _recent;
  bool get isLoading => _payments?.isLoading ?? false;
  Exception? get error => _payments?.error;

  void update(PaymentsProvider provider) {
    if (!identical(_payments, provider)) {
      _payments = provider;
    }
    _rebuild();
  }

  void _rebuild() {
    final operations = (_payments?.payments ?? const [])
        .map(mapPaymentToOperation)
        .toList();
    _recent = sortOperations(operations).take(5).toList();
    notifyListeners();
  }
}
