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