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 com.google.android.material.snackbar.Snackbar;
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;
40 import java.util.ArrayList;
41 import java.util.Locale;
43 import static net.ktnx.mobileledger.utils.Logger.debug;
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) {
55 int size = model.getAccountCount();
57 Logger.debug("new-transaction",
58 String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
62 NewTransactionItemsAdapter adapter = this;
64 touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
66 public boolean isLongPressDragEnabled() {
70 public boolean canDropOver(@NonNull RecyclerView recyclerView,
71 @NonNull RecyclerView.ViewHolder current,
72 @NonNull RecyclerView.ViewHolder target) {
73 final int adapterPosition = target.getAdapterPosition();
75 // first and last items are immovable
76 if (adapterPosition == 0)
78 if (adapterPosition == adapter.getItemCount() - 1)
81 return super.canDropOver(recyclerView, current, target);
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);
92 if (viewModel.getAccountCount() > 2) {
93 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
94 ItemTouchHelper.START | ItemTouchHelper.END);
101 public boolean onMove(@NonNull RecyclerView recyclerView,
102 @NonNull RecyclerView.ViewHolder viewHolder,
103 @NonNull RecyclerView.ViewHolder target) {
105 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
106 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
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);
119 public void setProfile(MobileLedgerProfile profile) {
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;
133 public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
134 LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
135 .inflate(R.layout.new_transaction_row,
138 return new NewTransactionItemHolder(row, this);
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()
150 public int getItemCount() {
151 return model.getAccountCount() + 2;
153 boolean accountListIsEmpty() {
154 for (int i = 0; i < model.getAccountCount(); i++) {
155 LedgerTransactionAccount acc = model.getAccount(i);
156 if (!acc.getAccountName()
159 if (acc.isAmountSet())
166 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
167 super.onAttachedToRecyclerView(recyclerView);
168 this.recyclerView = recyclerView;
169 touchHelper.attachToRecyclerView(recyclerView);
172 public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
173 touchHelper.attachToRecyclerView(null);
174 super.onDetachedFromRecyclerView(recyclerView);
175 this.recyclerView = null;
177 public void descriptionSelected(String description) {
178 debug("descr selected", description);
179 if (!accountListIsEmpty())
182 String accFilter = mProfile.getPreferredAccountsFilter();
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);
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());
198 sb.append(" ORDER BY date desc limit 1");
200 final String sql = sb.toString();
202 debug("descr", params.toString());
204 try (Cursor c = App.getDatabase()
205 .rawQuery(sql, params.toArray(new String[]{})))
210 String profileUUID = c.getString(0);
211 int transactionId = c.getInt(1);
212 LedgerTransaction tr;
213 MobileLedgerProfile profile = Data.getProfile(profileUUID);
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,
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);
234 item = model.getItem(i + 1);
237 .setAccountName(acc.getAccountName());
238 if (acc.isAmountSet()) {
240 .setAmount(acc.getAmount());
241 if (acc.getAmount() < 0) {
242 if (firstNegative == null) {
243 firstNegative = item;
244 singleNegativeIndex = i;
247 singleNegativeIndex = -1;
250 if (firstPositive == null) {
251 firstPositive = item;
252 singlePositiveIndex = i;
255 singlePositiveIndex = -1;
261 notifyItemChanged(i + 1);
264 if (singleNegativeIndex != -1) {
265 firstNegative.getAccount()
267 model.moveItemLast(singleNegativeIndex);
269 else if (singlePositiveIndex != -1) {
270 firstPositive.getAccount()
272 model.moveItemLast(singlePositiveIndex);
275 model.checkTransactionSubmittable(this);
276 model.setFocusedItem(1);
278 public void toggleAllEditing(boolean editable) {
279 // item 0 is the header
280 for (int i = 0; i <= model.getAccountCount(); i++) {
282 .setEditable(editable);
283 notifyItemChanged(i);
284 // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
287 public void reset() {
288 int presentItemCount = model.getAccountCount();
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
295 public void updateFocusedItem(int position) {
296 model.updateFocusedItem(position);
298 public void noteFocusIsOnAccount(int position) {
299 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
301 public void noteFocusIsOnAmount(int position) {
302 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
304 public void noteFocusIsOnComment(int position) {
305 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
307 public void toggleComment(int position) {
308 model.toggleComment(position);