import 'package:flutter/foundation.dart';

import 'package:pshared/provider/ledger.dart';


class LedgerBalanceMaskController with ChangeNotifier {
  String? _orgRef;
  final Set<String> _maskedBalanceRefs = <String>{};
  Set<String> _knownAccountRefs = <String>{};

  void update(LedgerAccountsProvider accountsProvider) {
    final nextOrgRef = accountsProvider.organizationRef;
    final orgChanged = nextOrgRef != _orgRef;

    if (orgChanged) {
      _orgRef = nextOrgRef;
      _maskedBalanceRefs.clear();
      _knownAccountRefs = <String>{};
    }

    final refs = accountsProvider.accounts.map((a) => a.ledgerAccountRef).toSet();
    _maskedBalanceRefs.removeWhere((id) => !refs.contains(id));

    final newRefs = refs.difference(_knownAccountRefs);
    if (newRefs.isNotEmpty) {
      _maskedBalanceRefs.addAll(newRefs);
    }
    _knownAccountRefs = refs;

    notifyListeners();
  }

  bool isBalanceMasked(String ledgerAccountRef) => _maskedBalanceRefs.contains(ledgerAccountRef);
  bool isBalanceVisible(String ledgerAccountRef) => !isBalanceMasked(ledgerAccountRef);

  void toggleBalanceMask(String ledgerAccountRef) {
    final existed = _maskedBalanceRefs.remove(ledgerAccountRef);
    if (!existed) _maskedBalanceRefs.add(ledgerAccountRef);
    notifyListeners();
  }

  void unmaskAllBalances() {
    _maskedBalanceRefs.clear();
    notifyListeners();
  }
}
