import 'package:rxdart/subjects.dart';
import 'package:krezus/repositories/json/json_repository.dart';
import 'package:krezus/repositories/transactions/models/transaction.dart';
import 'package:krezus/repositories/transactions/models/transactions.dart';

class TransactionsRepository {

  final JsonRepository _jsonRepository;
  final _transactionsController = BehaviorSubject<List<Transaction>>.seeded(const []);

  TransactionsRepository({
    required jsonRepository,
  }) : _jsonRepository = jsonRepository;

  List<Transaction> getTransactions() {
    return _transactionsController.value;
  }

  Stream<List<Transaction>> getTransactionsStream() {
    return _transactionsController.asBroadcastStream();
  }

  Future<void> loadTransactions() async {
    Transactions transactions = await _jsonRepository.loadJson(Transactions(), TransactionsFactory());
    _transactionsController.add(transactions.transactions);
  }

  void saveTransactions(List<Transaction> transactionsList) {
    Transactions transactions = Transactions(transactions: transactionsList);
    _jsonRepository.saveJson(transactions);
    _transactionsController.add(transactionsList);
  }

  void deleteTransactions() {
    Transactions transactions = Transactions();
    _jsonRepository.saveJson(transactions);
    _transactionsController.add([]);
  }
}