| 1 | import 'package:cw_core/utils/print_verbose.dart'; |
| 2 | import 'package:cw_core/wownero_amount_format.dart'; |
| 3 | import 'package:mobx/mobx.dart'; |
| 4 | import 'package:cw_core/account.dart'; |
| 5 | import 'package:cw_wownero/api/account_list.dart' as account_list; |
| 6 | import 'package:monero/wownero.dart' as wownero; |
| 7 | |
| 8 | part 'wownero_account_list.g.dart'; |
| 9 | |
| 10 | class WowneroAccountList = WowneroAccountListBase with _$WowneroAccountList; |
| 11 | |
| 12 | abstract class WowneroAccountListBase with Store { |
| 13 | WowneroAccountListBase() |
| 14 | : accounts = ObservableList<Account>(), |
| 15 | _isRefreshing = false, |
| 16 | _isUpdating = false { |
| 17 | refresh(); |
| 18 | } |
| 19 | |
| 20 | @observable |
| 21 | ObservableList<Account> accounts; |
| 22 | bool _isRefreshing; |
| 23 | bool _isUpdating; |
| 24 | |
| 25 | void update() async { |
| 26 | if (_isUpdating) { |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | try { |
| 31 | _isUpdating = true; |
| 32 | refresh(); |
| 33 | final accounts = getAll(); |
| 34 | |
| 35 | if (accounts.isNotEmpty) { |
| 36 | this.accounts.clear(); |
| 37 | this.accounts.addAll(accounts); |
| 38 | } |
| 39 | |
| 40 | _isUpdating = false; |
| 41 | } catch (e) { |
| 42 | _isUpdating = false; |
| 43 | rethrow; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | List<Account> getAll() => account_list.getAllAccount().map((accountRow) { |
| 48 | final balance = wownero.SubaddressAccountRow_getUnlockedBalance(accountRow); |
| 49 | |
| 50 | return Account( |
| 51 | id: wownero.SubaddressAccountRow_getRowId(accountRow), |
| 52 | label: wownero.SubaddressAccountRow_getLabel(accountRow), |
| 53 | balance: wowneroAmountToString(amount: wownero.Wallet_amountFromString(balance)), |
| 54 | ); |
| 55 | }).toList(); |
| 56 | |
| 57 | Future<void> addAccount({required String label}) async { |
| 58 | await account_list.addAccount(label: label); |
| 59 | update(); |
| 60 | } |
| 61 | |
| 62 | Future<void> setLabelAccount({required int accountIndex, required String label}) async { |
| 63 | await account_list.setLabelForAccount(accountIndex: accountIndex, label: label); |
| 64 | update(); |
| 65 | } |
| 66 | |
| 67 | void refresh() { |
| 68 | if (_isRefreshing) { |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | try { |
| 73 | _isRefreshing = true; |
| 74 | account_list.refreshAccounts(); |
| 75 | _isRefreshing = false; |
| 76 | } catch (e) { |
| 77 | _isRefreshing = false; |
| 78 | printV(e); |
| 79 | rethrow; |
| 80 | } |
| 81 | } |
| 82 | } |