]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/account_summary/AccountSummaryAdapter.java
convert the last update global header to a list header
[mobile-ledger-staging.git] / app / src / main / java / net / ktnx / mobileledger / ui / account_summary / AccountSummaryAdapter.java
1 /*
2  * Copyright © 2020 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 android.content.Context;
21 import android.content.res.Resources;
22 import android.text.TextUtils;
23 import android.text.format.DateUtils;
24 import android.view.LayoutInflater;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.widget.ImageView;
28 import android.widget.TextView;
29
30 import androidx.annotation.NonNull;
31 import androidx.appcompat.app.AlertDialog;
32 import androidx.constraintlayout.widget.ConstraintLayout;
33 import androidx.recyclerview.widget.AsyncListDiffer;
34 import androidx.recyclerview.widget.DiffUtil;
35 import androidx.recyclerview.widget.RecyclerView;
36
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DbOpQueue;
39 import net.ktnx.mobileledger.model.AccountListItem;
40 import net.ktnx.mobileledger.model.Data;
41 import net.ktnx.mobileledger.model.LedgerAccount;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.ui.MainModel;
44 import net.ktnx.mobileledger.ui.activity.MainActivity;
45 import net.ktnx.mobileledger.utils.Locker;
46
47 import org.jetbrains.annotations.NotNull;
48
49 import java.util.List;
50 import java.util.Locale;
51 import java.util.Observer;
52
53 import static net.ktnx.mobileledger.utils.Logger.debug;
54
55 public class AccountSummaryAdapter
56         extends RecyclerView.Adapter<AccountSummaryAdapter.LedgerRowHolder> {
57     public static final int AMOUNT_LIMIT = 3;
58     private final AsyncListDiffer<AccountListItem> listDiffer;
59     private final MainModel model;
60     AccountSummaryAdapter(MainModel model) {
61         this.model = model;
62
63         listDiffer = new AsyncListDiffer<>(this, new DiffUtil.ItemCallback<AccountListItem>() {
64             @Override
65             public boolean areItemsTheSame(@NotNull AccountListItem oldItem,
66                                            @NotNull AccountListItem newItem) {
67                 final AccountListItem.Type oldType = oldItem.getType();
68                 final AccountListItem.Type newType = newItem.getType();
69                 if (oldType == AccountListItem.Type.HEADER) {
70                     return newType == AccountListItem.Type.HEADER;
71                 }
72                 if (oldType != newType)
73                     return false;
74
75                 return TextUtils.equals(oldItem.getAccount()
76                                                .getName(), newItem.getAccount()
77                                                                   .getName());
78             }
79             @Override
80             public boolean areContentsTheSame(@NotNull AccountListItem oldItem,
81                                               @NotNull AccountListItem newItem) {
82                 if (oldItem.getType()
83                            .equals(AccountListItem.Type.HEADER))
84                     return true;
85                 return oldItem.getAccount()
86                               .equals(newItem.getAccount());
87             }
88         });
89     }
90
91     public void onBindViewHolder(@NonNull LedgerRowHolder holder, int position) {
92         holder.bindToAccount(listDiffer.getCurrentList()
93                                        .get(position));
94     }
95
96     @NonNull
97     @Override
98     public LedgerRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
99         View row = LayoutInflater.from(parent.getContext())
100                                  .inflate(R.layout.account_summary_row, parent, false);
101         return new LedgerRowHolder(row);
102     }
103
104     @Override
105     public int getItemCount() {
106         return listDiffer.getCurrentList()
107                          .size();
108     }
109     public void setAccounts(List<AccountListItem> newList) {
110         listDiffer.submitList(newList);
111     }
112     class LedgerRowHolder extends RecyclerView.ViewHolder {
113         private final TextView tvAccountName, tvAccountAmounts;
114         private final ConstraintLayout row;
115         private final View expanderContainer;
116         private final View amountExpanderContainer;
117         private final View lLastUpdate;
118         private final TextView tvLastUpdate;
119         private final View vAccountNameLayout;
120         LedgerAccount mAccount;
121         private AccountListItem.Type lastType;
122         private Observer lastUpdateObserver;
123         public LedgerRowHolder(@NonNull View itemView) {
124             super(itemView);
125
126             row = itemView.findViewById(R.id.account_summary_row);
127             vAccountNameLayout = itemView.findViewById(R.id.account_name_layout);
128             tvAccountName = itemView.findViewById(R.id.account_row_acc_name);
129             tvAccountAmounts = itemView.findViewById(R.id.account_row_acc_amounts);
130             expanderContainer = itemView.findViewById(R.id.account_expander_container);
131             ImageView expander = itemView.findViewById(R.id.account_expander);
132             amountExpanderContainer =
133                     itemView.findViewById(R.id.account_row_amounts_expander_container);
134             lLastUpdate = itemView.findViewById(R.id.last_update_container);
135             tvLastUpdate = itemView.findViewById(R.id.last_update_text);
136
137             itemView.setOnLongClickListener(this::onItemLongClick);
138             tvAccountName.setOnLongClickListener(this::onItemLongClick);
139             tvAccountAmounts.setOnLongClickListener(this::onItemLongClick);
140             expanderContainer.setOnLongClickListener(this::onItemLongClick);
141             expander.setOnLongClickListener(this::onItemLongClick);
142             row.setOnLongClickListener(this::onItemLongClick);
143
144             tvAccountName.setOnClickListener(v -> toggleAccountExpanded());
145             expanderContainer.setOnClickListener(v -> toggleAccountExpanded());
146             expander.setOnClickListener(v -> toggleAccountExpanded());
147             tvAccountAmounts.setOnClickListener(v -> toggleAmountsExpanded());
148
149         }
150         private void toggleAccountExpanded() {
151             if (!mAccount.hasSubAccounts())
152                 return;
153             debug("accounts", "Account expander clicked");
154
155             // make sure we use the same object as the one in the allAccounts list
156             MobileLedgerProfile profile = mAccount.getProfile();
157             if (profile == null) {
158                 return;
159             }
160             try (Locker ignored = model.lockAccountsForWriting()) {
161                 LedgerAccount realAccount = model.locateAccount(mAccount.getName());
162                 if (realAccount == null)
163                     return;
164
165                 mAccount = realAccount;
166                 mAccount.toggleExpanded();
167             }
168             expanderContainer.animate()
169                              .rotation(mAccount.isExpanded() ? 0 : 180);
170             model.updateDisplayedAccounts();
171
172             DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
173                     new Object[]{mAccount.isExpanded(), mAccount.getName(), profile.getUuid()
174                     });
175
176         }
177         private void toggleAmountsExpanded() {
178             if (mAccount.getAmountCount() <= AMOUNT_LIMIT)
179                 return;
180
181             mAccount.toggleAmountsExpanded();
182             if (mAccount.amountsExpanded()) {
183                 tvAccountAmounts.setText(mAccount.getAmountsString());
184                 amountExpanderContainer.setVisibility(View.GONE);
185             }
186             else {
187                 tvAccountAmounts.setText(mAccount.getAmountsString(AMOUNT_LIMIT));
188                 amountExpanderContainer.setVisibility(View.VISIBLE);
189             }
190
191             MobileLedgerProfile profile = mAccount.getProfile();
192             if (profile == null)
193                 return;
194
195             DbOpQueue.add("update accounts set amounts_expanded=? where name=? and profile=?",
196                     new Object[]{mAccount.amountsExpanded(), mAccount.getName(), profile.getUuid()
197                     });
198
199         }
200         private boolean onItemLongClick(View v) {
201             MainActivity activity = (MainActivity) v.getContext();
202             AlertDialog.Builder builder = new AlertDialog.Builder(activity);
203             final String accountName = mAccount.getName();
204             builder.setTitle(accountName);
205             builder.setItems(R.array.acc_ctx_menu, (dialog, which) -> {
206                 if (which == 0) {// show transactions
207                     activity.showAccountTransactions(accountName);
208                 }
209                 else {
210                     throw new RuntimeException(String.format("Unknown menu item id (%d)", which));
211                 }
212                 dialog.dismiss();
213             });
214             builder.show();
215             return true;
216         }
217         public void bindToAccount(AccountListItem item) {
218             final AccountListItem.Type newType = item.getType();
219             setType(newType);
220
221             switch (newType) {
222                 case ACCOUNT:
223                     LedgerAccount acc = item.getAccount();
224
225                     debug("accounts", String.format(Locale.US, "Binding to '%s'", acc.getName()));
226                     Context ctx = row.getContext();
227                     Resources rm = ctx.getResources();
228                     mAccount = acc;
229
230                     row.setTag(acc);
231
232                     tvAccountName.setText(acc.getShortName());
233
234                     ConstraintLayout.LayoutParams lp =
235                             (ConstraintLayout.LayoutParams) tvAccountName.getLayoutParams();
236                     lp.setMarginStart(
237                             acc.getLevel() * rm.getDimensionPixelSize(R.dimen.thumb_row_height) /
238                             3);
239
240                     if (acc.hasSubAccounts()) {
241                         expanderContainer.setVisibility(View.VISIBLE);
242                         expanderContainer.setRotation(acc.isExpanded() ? 0 : 180);
243                     }
244                     else {
245                         expanderContainer.setVisibility(View.GONE);
246                     }
247
248                     int amounts = acc.getAmountCount();
249                     if ((amounts > AMOUNT_LIMIT) && !acc.amountsExpanded()) {
250                         tvAccountAmounts.setText(acc.getAmountsString(AMOUNT_LIMIT));
251                         amountExpanderContainer.setVisibility(View.VISIBLE);
252                     }
253                     else {
254                         tvAccountAmounts.setText(acc.getAmountsString());
255                         amountExpanderContainer.setVisibility(View.GONE);
256                     }
257
258                     break;
259                 case HEADER:
260                     setLastUpdateText(Data.lastUpdate.get());
261                     break;
262                 default:
263                     throw new IllegalStateException("Unexpected value: " + newType);
264             }
265
266         }
267         void setLastUpdateText(long lastUpdate) {
268             final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
269                                     DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
270             tvLastUpdate.setText((lastUpdate == 0) ? "----" : DateUtils.formatDateTime(
271                     tvLastUpdate.getContext(), lastUpdate, formatFlags));
272         }
273         private void initLastUpdateObserver() {
274             if (lastUpdateObserver != null)
275                 return;
276
277             lastUpdateObserver = (o, arg) -> setLastUpdateText(Data.lastUpdate.get());
278
279             Data.lastUpdate.addObserver(lastUpdateObserver);
280         }
281         private void dropLastUpdateObserver() {
282             if (lastUpdateObserver == null)
283                 return;
284
285             Data.lastUpdate.deleteObserver(lastUpdateObserver);
286             lastUpdateObserver = null;
287         }
288         private void setType(AccountListItem.Type newType) {
289             if (newType == lastType)
290                 return;
291
292             switch (newType) {
293                 case ACCOUNT:
294                     row.setLongClickable(true);
295                     amountExpanderContainer.setVisibility(View.VISIBLE);
296                     vAccountNameLayout.setVisibility(View.VISIBLE);
297                     tvAccountAmounts.setVisibility(View.VISIBLE);
298                     lLastUpdate.setVisibility(View.GONE);
299                     dropLastUpdateObserver();
300                     break;
301                 case HEADER:
302                     row.setLongClickable(false);
303                     tvAccountAmounts.setVisibility(View.GONE);
304                     amountExpanderContainer.setVisibility(View.GONE);
305                     vAccountNameLayout.setVisibility(View.GONE);
306                     lLastUpdate.setVisibility(View.VISIBLE);
307                     initLastUpdateObserver();
308                     break;
309                 default:
310                     throw new IllegalStateException("Unexpected value: " + newType);
311             }
312
313             lastType = newType;
314         }
315     }
316 }