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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.database.Cursor;
21 import android.view.LayoutInflater;
22 import android.view.ViewGroup;
23 import android.widget.LinearLayout;
25 import androidx.annotation.NonNull;
26 import androidx.recyclerview.widget.ItemTouchHelper;
27 import androidx.recyclerview.widget.RecyclerView;
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;
38 import java.util.ArrayList;
39 import java.util.Locale;
41 import static net.ktnx.mobileledger.utils.Logger.debug;
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) {
53 int size = model.getAccountCount();
55 Logger.debug("new-transaction",
56 String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
60 NewTransactionItemsAdapter adapter = this;
62 touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
64 public boolean isLongPressDragEnabled() {
68 public boolean canDropOver(@NonNull RecyclerView recyclerView,
69 @NonNull RecyclerView.ViewHolder current,
70 @NonNull RecyclerView.ViewHolder target) {
71 final int adapterPosition = target.getAdapterPosition();
73 // first and last items are immovable
74 if (adapterPosition == 0)
76 if (adapterPosition == adapter.getItemCount() - 1)
79 return super.canDropOver(recyclerView, current, target);
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);
97 public boolean onMove(@NonNull RecyclerView recyclerView,
98 @NonNull RecyclerView.ViewHolder viewHolder,
99 @NonNull RecyclerView.ViewHolder target) {
101 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
102 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
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);
115 public void setProfile(MobileLedgerProfile profile) {
121 int addRow(String commodity) {
122 final int newAccountCount = model.addAccount(new LedgerTransactionAccount("", commodity));
123 Logger.debug("new-transaction",
124 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
125 // the header is at position 0
126 notifyItemInserted(newAccountCount);
127 model.sendCountNotifications(); // needed after holders' positions have changed
128 return newAccountCount;
132 public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
133 LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
134 .inflate(R.layout.new_transaction_row,
137 return new NewTransactionItemHolder(row, this);
140 public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
141 Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
142 NewTransactionModel.Item item = model.getItem(position);
143 holder.setData(item);
144 Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
149 public int getItemCount() {
150 return model.getAccountCount() + 2;
152 boolean accountListIsEmpty() {
153 for (int i = 0; i < model.getAccountCount(); i++) {
154 LedgerTransactionAccount acc = model.getAccount(i);
155 if (!acc.getAccountName()
158 if (acc.isAmountSet())
165 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
166 super.onAttachedToRecyclerView(recyclerView);
167 this.recyclerView = recyclerView;
168 touchHelper.attachToRecyclerView(recyclerView);
171 public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
172 touchHelper.attachToRecyclerView(null);
173 super.onDetachedFromRecyclerView(recyclerView);
174 this.recyclerView = null;
176 public void descriptionSelected(String description) {
177 debug("descr selected", description);
178 if (!accountListIsEmpty())
181 String accFilter = mProfile.getPreferredAccountsFilter();
183 ArrayList<String> params = new ArrayList<>();
184 StringBuilder sb = new StringBuilder(
185 "select t.profile, t.id from transactions t where t.description=?");
186 params.add(description);
188 if (accFilter != null) {
189 sb.append(" AND EXISTS (")
190 .append("SELECT 1 FROM transaction_accounts ta ")
191 .append("WHERE ta.profile = t.profile")
192 .append(" AND ta.transaction_id = t.id")
193 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
194 params.add(accFilter.toUpperCase());
197 sb.append(" ORDER BY date desc limit 1");
199 final String sql = sb.toString();
201 debug("descr", params.toString());
203 try (Cursor c = App.getDatabase()
204 .rawQuery(sql, params.toArray(new String[]{})))
209 String profileUUID = c.getString(0);
210 int transactionId = c.getInt(1);
211 LedgerTransaction tr;
212 MobileLedgerProfile profile = Data.getProfile(profileUUID);
214 throw new RuntimeException(String.format(
215 "Unable to find profile %s, which is supposed to contain " +
216 "transaction %d with description %s", profileUUID, transactionId,
219 tr = profile.loadTransaction(transactionId);
220 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
221 NewTransactionModel.Item firstNegative = null;
222 NewTransactionModel.Item firstPositive = null;
223 int singleNegativeIndex = -1;
224 int singlePositiveIndex = -1;
225 int negativeCount = 0;
226 for (int i = 0; i < accounts.size(); i++) {
227 LedgerTransactionAccount acc = accounts.get(i);
228 NewTransactionModel.Item item;
229 if (model.getAccountCount() < i + 1) {
230 model.addAccount(acc);
231 notifyItemInserted(i + 1);
233 item = model.getItem(i + 1);
236 .setAccountName(acc.getAccountName());
237 if (acc.isAmountSet()) {
239 .setAmount(acc.getAmount());
240 if (acc.getAmount() < 0) {
241 if (firstNegative == null) {
242 firstNegative = item;
243 singleNegativeIndex = i;
246 singleNegativeIndex = -1;
249 if (firstPositive == null) {
250 firstPositive = item;
251 singlePositiveIndex = i;
254 singlePositiveIndex = -1;
260 notifyItemChanged(i + 1);
263 if (singleNegativeIndex != -1) {
264 firstNegative.getAccount()
266 model.moveItemLast(singleNegativeIndex);
268 else if (singlePositiveIndex != -1) {
269 firstPositive.getAccount()
271 model.moveItemLast(singlePositiveIndex);
274 model.checkTransactionSubmittable(this);
275 model.setFocusedItem(1);
277 public void toggleAllEditing(boolean editable) {
278 // item 0 is the header
279 for (int i = 0; i <= model.getAccountCount(); i++) {
281 .setEditable(editable);
282 notifyItemChanged(i);
283 // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
286 public void reset() {
287 int presentItemCount = model.getAccountCount();
289 notifyItemChanged(0); // header changed
290 notifyItemRangeChanged(1, 2); // the two empty rows
291 if (presentItemCount > 2)
292 notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
294 public void updateFocusedItem(int position) {
295 model.updateFocusedItem(position);
297 public void noteFocusIsOnAccount(int position) {
298 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
300 public void noteFocusIsOnAmount(int position) {
301 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
303 public void noteFocusIsOnComment(int position) {
304 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
306 public void toggleComment(int position) {
307 model.toggleComment(position);