]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
c9b9230e1235891ff0e018e1fe3a2cd32c7a68da
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemsAdapter.java
1 /*
2  * Copyright © 2019 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.activity;
19
20 import android.database.Cursor;
21 import android.view.LayoutInflater;
22 import android.view.ViewGroup;
23 import android.widget.LinearLayout;
24
25 import androidx.annotation.NonNull;
26 import androidx.recyclerview.widget.ItemTouchHelper;
27 import androidx.recyclerview.widget.RecyclerView;
28
29 import com.google.android.material.snackbar.Snackbar;
30
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.R;
33 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerTransaction;
36 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
37 import net.ktnx.mobileledger.model.MobileLedgerProfile;
38 import net.ktnx.mobileledger.utils.Logger;
39
40 import java.util.ArrayList;
41 import java.util.Locale;
42
43 import static net.ktnx.mobileledger.utils.Logger.debug;
44
45 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
46         implements DescriptionSelectedCallback {
47     NewTransactionModel model;
48     private MobileLedgerProfile mProfile;
49     private ItemTouchHelper touchHelper;
50     private RecyclerView recyclerView;
51     NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
52         super();
53         model = viewModel;
54         mProfile = profile;
55         int size = model.getAccountCount();
56         while (size < 2) {
57             Logger.debug("new-transaction",
58                     String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
59             size = addRow();
60         }
61
62         NewTransactionItemsAdapter adapter = this;
63
64         touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
65             @Override
66             public boolean isLongPressDragEnabled() {
67                 return true;
68             }
69             @Override
70             public boolean canDropOver(@NonNull RecyclerView recyclerView,
71                                        @NonNull RecyclerView.ViewHolder current,
72                                        @NonNull RecyclerView.ViewHolder target) {
73                 final int adapterPosition = target.getAdapterPosition();
74
75                 // first and last items are immovable
76                 if (adapterPosition == 0)
77                     return false;
78                 if (adapterPosition == adapter.getItemCount() - 1)
79                     return false;
80
81                 return super.canDropOver(recyclerView, current, target);
82             }
83             @Override
84             public int getMovementFlags(@NonNull RecyclerView recyclerView,
85                                         @NonNull RecyclerView.ViewHolder viewHolder) {
86                 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
87                 // the top item is always there (date and description)
88                 if (viewHolder.getAdapterPosition() > 0) {
89                     flags |= makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
90                             ItemTouchHelper.UP | ItemTouchHelper.DOWN);
91
92                     if (viewModel.getAccountCount() > 2) {
93                         flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
94                                 ItemTouchHelper.START | ItemTouchHelper.END);
95                     }
96                 }
97
98                 return flags;
99             }
100             @Override
101             public boolean onMove(@NonNull RecyclerView recyclerView,
102                                   @NonNull RecyclerView.ViewHolder viewHolder,
103                                   @NonNull RecyclerView.ViewHolder target) {
104
105                 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
106                 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
107                 return true;
108             }
109             @Override
110             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
111                 int pos = viewHolder.getAdapterPosition();
112                 viewModel.removeItem(pos - 1);
113                 notifyItemRemoved(pos);
114                 viewModel.sendCountNotifications(); // needed after items re-arrangement
115                 viewModel.checkTransactionSubmittable(adapter);
116             }
117         });
118     }
119     public void setProfile(MobileLedgerProfile profile) {
120         mProfile = profile;
121     }
122     int addRow() {
123         final int newAccountCount = model.addAccount(new LedgerTransactionAccount(""));
124         Logger.debug("new-transaction",
125                 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
126         // the header is at position 0
127         notifyItemInserted(newAccountCount);
128         model.sendCountNotifications(); // needed after holders' positions have changed
129         return newAccountCount;
130     }
131     @NonNull
132     @Override
133     public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
134         LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
135                                                         .inflate(R.layout.new_transaction_row,
136                                                                 parent, false);
137
138         return new NewTransactionItemHolder(row, this);
139     }
140     @Override
141     public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
142         Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
143         NewTransactionModel.Item item = model.getItem(position);
144         holder.setData(item);
145         Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
146                                                                                           .toString(),
147                 position));
148     }
149     @Override
150     public int getItemCount() {
151         return model.getAccountCount() + 2;
152     }
153     boolean accountListIsEmpty() {
154         for (int i = 0; i < model.getAccountCount(); i++) {
155             LedgerTransactionAccount acc = model.getAccount(i);
156             if (!acc.getAccountName()
157                     .isEmpty())
158                 return false;
159             if (acc.isAmountSet())
160                 return false;
161         }
162
163         return true;
164     }
165     @Override
166     public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
167         super.onAttachedToRecyclerView(recyclerView);
168         this.recyclerView = recyclerView;
169         touchHelper.attachToRecyclerView(recyclerView);
170     }
171     @Override
172     public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
173         touchHelper.attachToRecyclerView(null);
174         super.onDetachedFromRecyclerView(recyclerView);
175         this.recyclerView = null;
176     }
177     public void descriptionSelected(String description) {
178         debug("descr selected", description);
179         if (!accountListIsEmpty())
180             return;
181
182         String accFilter = mProfile.getPreferredAccountsFilter();
183
184         ArrayList<String> params = new ArrayList<>();
185         StringBuilder sb = new StringBuilder(
186                 "select t.profile, t.id from transactions t where t.description=?");
187         params.add(description);
188
189         if (accFilter != null) {
190             sb.append(" AND EXISTS (")
191               .append("SELECT 1 FROM transaction_accounts ta ")
192               .append("WHERE ta.profile = t.profile")
193               .append(" AND ta.transaction_id = t.id")
194               .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
195             params.add(accFilter.toUpperCase());
196         }
197
198         sb.append(" ORDER BY date desc limit 1");
199
200         final String sql = sb.toString();
201         debug("descr", sql);
202         debug("descr", params.toString());
203
204         try (Cursor c = App.getDatabase()
205                            .rawQuery(sql, params.toArray(new String[]{})))
206         {
207             if (!c.moveToNext())
208                 return;
209
210             String profileUUID = c.getString(0);
211             int transactionId = c.getInt(1);
212             LedgerTransaction tr;
213             MobileLedgerProfile profile = Data.getProfile(profileUUID);
214             if (profile == null)
215                 throw new RuntimeException(String.format(
216                         "Unable to find profile %s, which is supposed to contain " +
217                         "transaction %d with description %s", profileUUID, transactionId,
218                         description));
219
220             tr = profile.loadTransaction(transactionId);
221             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
222             NewTransactionModel.Item firstNegative = null;
223             NewTransactionModel.Item firstPositive = null;
224             int singleNegativeIndex = -1;
225             int singlePositiveIndex = -1;
226             int negativeCount = 0;
227             for (int i = 0; i < accounts.size(); i++) {
228                 LedgerTransactionAccount acc = accounts.get(i);
229                 NewTransactionModel.Item item;
230                 if (model.getAccountCount() < i + 1) {
231                     model.addAccount(acc);
232                     notifyItemInserted(i + 1);
233                 }
234                 item = model.getItem(i + 1);
235
236                 item.getAccount()
237                     .setAccountName(acc.getAccountName());
238                 if (acc.isAmountSet()) {
239                     item.getAccount()
240                         .setAmount(acc.getAmount());
241                     if (acc.getAmount() < 0) {
242                         if (firstNegative == null) {
243                             firstNegative = item;
244                             singleNegativeIndex = i;
245                         }
246                         else
247                             singleNegativeIndex = -1;
248                     }
249                     else {
250                         if (firstPositive == null) {
251                             firstPositive = item;
252                             singlePositiveIndex = i;
253                         }
254                         else
255                             singlePositiveIndex = -1;
256                     }
257                 }
258                 else
259                     item.getAccount()
260                         .resetAmount();
261                 notifyItemChanged(i + 1);
262             }
263
264             if (singleNegativeIndex != -1) {
265                 firstNegative.getAccount()
266                              .resetAmount();
267                 model.moveItemLast(singleNegativeIndex);
268             }
269             else if (singlePositiveIndex != -1) {
270                 firstPositive.getAccount()
271                              .resetAmount();
272                 model.moveItemLast(singlePositiveIndex);
273             }
274         }
275         model.checkTransactionSubmittable(this);
276         model.setFocusedItem(1);
277     }
278     public void toggleAllEditing(boolean editable) {
279         // item 0 is the header
280         for (int i = 0; i <= model.getAccountCount(); i++) {
281             model.getItem(i)
282                  .setEditable(editable);
283             notifyItemChanged(i);
284             // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
285         }
286     }
287     public void reset() {
288         int presentItemCount = model.getAccountCount();
289         model.reset();
290         notifyItemChanged(0);       // header changed
291         notifyItemRangeChanged(1, 2);    // the two empty rows
292         if (presentItemCount > 2)
293             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
294     }
295     public void updateFocusedItem(int position) {
296         model.updateFocusedItem(position);
297     }
298     public void noteFocusIsOnAccount(int position) {
299         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
300     }
301     public void noteFocusIsOnAmount(int position) {
302         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
303     }
304     public void noteFocusIsOnComment(int position) {
305         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
306     }
307     public void toggleComment(int position) {
308         model.toggleComment(position);
309     }
310 }