]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/account_summary/AccountSummaryAdapter.java
add ability to hide all-zero accounts from the account list
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / account_summary / AccountSummaryAdapter.java
1 /*
2  * Copyright © 2024 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.account_summary;
19
20 import static net.ktnx.mobileledger.utils.Logger.debug;
21
22 import android.content.res.Resources;
23 import android.view.LayoutInflater;
24 import android.view.View;
25 import android.view.ViewGroup;
26
27 import androidx.annotation.NonNull;
28 import androidx.annotation.Nullable;
29 import androidx.appcompat.app.AlertDialog;
30 import androidx.constraintlayout.widget.ConstraintLayout;
31 import androidx.lifecycle.LifecycleOwner;
32 import androidx.recyclerview.widget.AsyncListDiffer;
33 import androidx.recyclerview.widget.DiffUtil;
34 import androidx.recyclerview.widget.RecyclerView;
35
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.dao.BaseDAO;
38 import net.ktnx.mobileledger.databinding.AccountListRowBinding;
39 import net.ktnx.mobileledger.databinding.AccountListSummaryRowBinding;
40 import net.ktnx.mobileledger.db.Account;
41 import net.ktnx.mobileledger.db.DB;
42 import net.ktnx.mobileledger.model.AccountListItem;
43 import net.ktnx.mobileledger.model.LedgerAccount;
44 import net.ktnx.mobileledger.ui.activity.MainActivity;
45 import net.ktnx.mobileledger.utils.Logger;
46 import net.ktnx.mobileledger.utils.Misc;
47
48 import org.jetbrains.annotations.NotNull;
49
50 import java.util.List;
51 import java.util.Locale;
52
53 public class AccountSummaryAdapter extends RecyclerView.Adapter<AccountSummaryAdapter.RowHolder> {
54     public static final int AMOUNT_LIMIT = 3;
55     private static final int ITEM_TYPE_HEADER = 1;
56     private static final int ITEM_TYPE_ACCOUNT = 2;
57     private final AsyncListDiffer<AccountListItem> listDiffer;
58
59     AccountSummaryAdapter() {
60         setHasStableIds(true);
61
62         listDiffer = new AsyncListDiffer<>(this, new DiffUtil.ItemCallback<AccountListItem>() {
63             @Nullable
64             @Override
65             public Object getChangePayload(@NonNull AccountListItem oldItem,
66                                            @NonNull AccountListItem newItem) {
67                 Change changes = new Change();
68
69                 final LedgerAccount oldAcc = oldItem.toAccount()
70                                                     .getAccount();
71                 final LedgerAccount newAcc = newItem.toAccount()
72                                                     .getAccount();
73
74                 if (!Misc.equalStrings(oldAcc.getName(), newAcc.getName()))
75                     changes.add(Change.NAME);
76
77                 if (oldAcc.getLevel() != newAcc.getLevel())
78                     changes.add(Change.LEVEL);
79
80                 if (oldAcc.isExpanded() != newAcc.isExpanded())
81                     changes.add(Change.EXPANDED);
82
83                 if (oldAcc.amountsExpanded() != newAcc.amountsExpanded())
84                     changes.add(Change.EXPANDED_AMOUNTS);
85
86                 if (!oldAcc.getAmountsString()
87                            .equals(newAcc.getAmountsString()))
88                     changes.add(Change.AMOUNTS);
89
90                 return changes.toPayload();
91             }
92             @Override
93             public boolean areItemsTheSame(@NotNull AccountListItem oldItem,
94                                            @NotNull AccountListItem newItem) {
95                 final AccountListItem.Type oldType = oldItem.getType();
96                 final AccountListItem.Type newType = newItem.getType();
97                 if (oldType != newType)
98                     return false;
99                 if (oldType == AccountListItem.Type.HEADER)
100                     return true;
101
102                 return oldItem.toAccount()
103                               .getAccount()
104                               .getId() == newItem.toAccount()
105                                                  .getAccount()
106                                                  .getId();
107             }
108             @Override
109             public boolean areContentsTheSame(@NotNull AccountListItem oldItem,
110                                               @NotNull AccountListItem newItem) {
111                 return oldItem.sameContent(newItem);
112             }
113         });
114     }
115     @Override
116     public long getItemId(int position) {
117         if (position == 0)
118             return 0;
119         return listDiffer.getCurrentList()
120                          .get(position)
121                          .toAccount()
122                          .getAccount()
123                          .getId();
124     }
125     @Override
126     public void onBindViewHolder(@NonNull RowHolder holder, int position,
127                                  @NonNull List<Object> payloads) {
128         holder.bind(listDiffer.getCurrentList()
129                               .get(position), payloads);
130         super.onBindViewHolder(holder, position, payloads);
131     }
132     public void onBindViewHolder(@NonNull RowHolder holder, int position) {
133         holder.bind(listDiffer.getCurrentList()
134                               .get(position), null);
135     }
136     @NonNull
137     @Override
138     public RowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
139         final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
140
141         final RowHolder result;
142         switch (viewType) {
143             case ITEM_TYPE_HEADER:
144                 result = new HeaderRowHolder(
145                         AccountListSummaryRowBinding.inflate(inflater, parent, false));
146                 break;
147             case ITEM_TYPE_ACCOUNT:
148                 result = new AccountRowHolder(
149                         AccountListRowBinding.inflate(inflater, parent, false));
150                 break;
151             default:
152                 throw new IllegalStateException("Unexpected value: " + viewType);
153         }
154
155 //        Logger.debug("acc-ui", "Creating " + result);
156         return result;
157     }
158     @Override
159     public int getItemCount() {
160         return listDiffer.getCurrentList()
161                          .size();
162     }
163     @Override
164     public int getItemViewType(int position) {
165         return (position == 0) ? ITEM_TYPE_HEADER : ITEM_TYPE_ACCOUNT;
166     }
167     public void setAccounts(List<AccountListItem> newList) {
168         Misc.onMainThread(() -> listDiffer.submitList(newList));
169     }
170     static class Change {
171         static final int NAME = 1;
172         static final int EXPANDED = 1 << 1;
173         static final int LEVEL = 1 << 2;
174         static final int EXPANDED_AMOUNTS = 1 << 3;
175         static final int AMOUNTS = 1 << 4;
176         private int value = 0;
177         public Change() {
178         }
179         public Change(int initialValue) {
180             value = initialValue;
181         }
182         public void add(int bits) {
183             value = value | bits;
184         }
185         public void add(Change change) {
186             value = value | change.value;
187         }
188         public void remove(int bits) {
189             value = value & (~bits);
190         }
191         public void remove(Change change) {
192             value = value & (~change.value);
193         }
194         public Change toPayload() {
195             if (value == 0)
196                 return null;
197             return this;
198         }
199         public boolean has(int bits) {
200             return value == 0 || (value & bits) == bits;
201         }
202     }
203
204     static abstract class RowHolder extends RecyclerView.ViewHolder {
205         public RowHolder(@NonNull View itemView) {
206             super(itemView);
207         }
208         public abstract void bind(AccountListItem accountListItem, @Nullable List<Object> payloads);
209     }
210
211     static class HeaderRowHolder extends RowHolder {
212         private final AccountListSummaryRowBinding b;
213         public HeaderRowHolder(@NonNull AccountListSummaryRowBinding binding) {
214             super(binding.getRoot());
215             b = binding;
216         }
217         @Override
218         public void bind(AccountListItem item, @Nullable List<Object> payloads) {
219             Resources r = itemView.getResources();
220 //            Logger.debug("acc", itemView.getContext()
221 //                                        .toString());
222             ((AccountListItem.Header) item).getText()
223                                            .observe((LifecycleOwner) itemView.getContext(),
224                                                    b.lastUpdateText::setText);
225         }
226     }
227
228     class AccountRowHolder extends AccountSummaryAdapter.RowHolder {
229         private final AccountListRowBinding b;
230         public AccountRowHolder(@NonNull AccountListRowBinding binding) {
231             super(binding.getRoot());
232             b = binding;
233
234             itemView.setOnLongClickListener(this::onItemLongClick);
235             b.accountRowAccName.setOnLongClickListener(this::onItemLongClick);
236             b.accountRowAccAmounts.setOnLongClickListener(this::onItemLongClick);
237             b.accountExpanderContainer.setOnLongClickListener(this::onItemLongClick);
238             b.accountExpander.setOnLongClickListener(this::onItemLongClick);
239
240             b.accountRowAccName.setOnClickListener(v -> toggleAccountExpanded());
241             b.accountExpanderContainer.setOnClickListener(v -> toggleAccountExpanded());
242             b.accountExpander.setOnClickListener(v -> toggleAccountExpanded());
243             b.accountRowAccAmounts.setOnClickListener(v -> toggleAmountsExpanded());
244         }
245         private void toggleAccountExpanded() {
246             LedgerAccount account = getAccount();
247             if (!account.hasSubAccounts())
248                 return;
249             debug("accounts", "Account expander clicked");
250
251             BaseDAO.runAsync(() -> {
252                 Account dbo = account.toDBO();
253                 dbo.setExpanded(!dbo.isExpanded());
254                 Logger.debug("accounts",
255                         String.format(Locale.ROOT, "%s (%d) → %s", account.getName(), dbo.getId(),
256                                 dbo.isExpanded() ? "expanded" : "collapsed"));
257                 DB.get()
258                   .getAccountDAO()
259                   .updateSync(dbo);
260             });
261         }
262         @NotNull
263         private LedgerAccount getAccount() {
264             return listDiffer.getCurrentList()
265                              .get(getBindingAdapterPosition())
266                              .toAccount()
267                              .getAccount();
268         }
269         private void toggleAmountsExpanded() {
270             LedgerAccount account = getAccount();
271             if (account.getAmountCount() <= AMOUNT_LIMIT)
272                 return;
273
274             account.toggleAmountsExpanded();
275             if (account.amountsExpanded()) {
276                 b.accountRowAccAmounts.setText(account.getAmountsString());
277                 b.accountRowAmountsExpanderContainer.setVisibility(View.GONE);
278             }
279             else {
280                 b.accountRowAccAmounts.setText(account.getAmountsString(AMOUNT_LIMIT));
281                 b.accountRowAmountsExpanderContainer.setVisibility(View.VISIBLE);
282             }
283
284             BaseDAO.runAsync(() -> {
285                 Account dbo = account.toDBO();
286                 DB.get()
287                   .getAccountDAO()
288                   .updateSync(dbo);
289             });
290         }
291         private boolean onItemLongClick(View v) {
292             MainActivity activity = (MainActivity) v.getContext();
293             AlertDialog.Builder builder = new AlertDialog.Builder(activity);
294             final String accountName = getAccount().getName();
295             builder.setTitle(accountName);
296             builder.setItems(R.array.acc_ctx_menu, (dialog, which) -> {
297                 if (which == 0) {// show transactions
298                     activity.showAccountTransactions(accountName);
299                 }
300                 else {
301                     throw new RuntimeException(String.format("Unknown menu item id (%d)", which));
302                 }
303                 dialog.dismiss();
304             });
305             builder.show();
306             return true;
307         }
308         @Override
309         public void bind(AccountListItem item, @Nullable List<Object> payloads) {
310             LedgerAccount acc = item.toAccount()
311                                     .getAccount();
312
313             Change changes = new Change();
314             if (payloads != null) {
315                 for (Object p : payloads) {
316                     if (p instanceof Change)
317                         changes.add((Change) p);
318                 }
319             }
320 //            debug("accounts",
321 //                    String.format(Locale.US, "Binding '%s' to %s", acc.getName(), this));
322
323             Resources rm = b.getRoot()
324                             .getContext()
325                             .getResources();
326
327             if (changes.has(Change.NAME))
328                 b.accountRowAccName.setText(acc.getShortName());
329
330             if (changes.has(Change.LEVEL)) {
331                 ConstraintLayout.LayoutParams lp =
332                         (ConstraintLayout.LayoutParams) b.flowWrapper.getLayoutParams();
333                 lp.setMarginStart(
334                         acc.getLevel() * rm.getDimensionPixelSize(R.dimen.thumb_row_height) / 3);
335             }
336
337             if (acc.hasSubAccounts()) {
338                 b.accountExpanderContainer.setVisibility(View.VISIBLE);
339
340                 if (changes.has(Change.EXPANDED)) {
341                     int wantedRotation = acc.isExpanded() ? 0 : 180;
342                     if (b.accountExpanderContainer.getRotation() != wantedRotation) {
343 //                        Logger.debug("acc-ui",
344 //                                String.format(Locale.ROOT, "Rotating %s to %d", acc.getName(),
345 //                                        wantedRotation));
346                         b.accountExpanderContainer.animate()
347                                                   .rotation(wantedRotation);
348                     }
349                 }
350             }
351             else {
352                 b.accountExpanderContainer.setVisibility(View.GONE);
353             }
354
355             if (changes.has(Change.EXPANDED_AMOUNTS)) {
356                 int amounts = acc.getAmountCount();
357                 if ((amounts > AMOUNT_LIMIT) && !acc.amountsExpanded()) {
358                     b.accountRowAccAmounts.setText(acc.getAmountsString(AMOUNT_LIMIT));
359                     b.accountRowAmountsExpanderContainer.setVisibility(View.VISIBLE);
360                 }
361                 else {
362                     b.accountRowAccAmounts.setText(acc.getAmountsString());
363                     b.accountRowAmountsExpanderContainer.setVisibility(View.GONE);
364                 }
365             }
366         }
367     }
368 }