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) {
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;
129 public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
130 LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
131 .inflate(R.layout.new_transaction_row,
134 return new NewTransactionItemHolder(row, this);
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()
146 public int getItemCount() {
147 return model.getAccountCount() + 2;
149 boolean accountListIsEmpty() {
150 for (int i = 0; i < model.getAccountCount(); i++) {
151 LedgerTransactionAccount acc = model.getAccount(i);
152 if (!acc.getAccountName()
155 if (acc.isAmountSet())
162 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
163 super.onAttachedToRecyclerView(recyclerView);
164 this.recyclerView = recyclerView;
165 touchHelper.attachToRecyclerView(recyclerView);
168 public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
169 touchHelper.attachToRecyclerView(null);
170 super.onDetachedFromRecyclerView(recyclerView);
171 this.recyclerView = null;
173 public void descriptionSelected(String description) {
174 debug("descr selected", description);
175 if (!accountListIsEmpty())
178 String accFilter = mProfile.getPreferredAccountsFilter();
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);
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());
194 sb.append(" ORDER BY date desc limit 1");
196 final String sql = sb.toString();
198 debug("descr", params.toString());
200 try (Cursor c = App.getDatabase()
201 .rawQuery(sql, params.toArray(new String[]{})))
206 String profileUUID = c.getString(0);
207 int transactionId = c.getInt(1);
208 LedgerTransaction tr;
209 MobileLedgerProfile profile = Data.getProfile(profileUUID);
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,
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);
230 item = model.getItem(i + 1);
233 .setAccountName(acc.getAccountName());
234 if (acc.isAmountSet()) {
236 .setAmount(acc.getAmount());
237 if (acc.getAmount() < 0) {
238 if (firstNegative == null) {
239 firstNegative = item;
240 singleNegativeIndex = i;
243 singleNegativeIndex = -1;
246 if (firstPositive == null) {
247 firstPositive = item;
248 singlePositiveIndex = i;
251 singlePositiveIndex = -1;
257 notifyItemChanged(i + 1);
260 if (singleNegativeIndex != -1) {
261 firstNegative.getAccount()
263 model.moveItemLast(singleNegativeIndex);
265 else if (singlePositiveIndex != -1) {
266 firstPositive.getAccount()
268 model.moveItemLast(singlePositiveIndex);
271 model.checkTransactionSubmittable(this);
272 model.setFocusedItem(1);
274 public void toggleAllEditing(boolean editable) {
275 // item 0 is the header
276 for (int i = 0; i <= model.getAccountCount(); i++) {
278 .setEditable(editable);
279 notifyItemChanged(i);
280 // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
283 public void reset() {
284 int presentItemCount = model.getAccountCount();
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
291 public void updateFocusedItem(int position) {
292 model.updateFocusedItem(position);
294 public void noteFocusIsOnAccount(int position) {
295 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
297 public void noteFocusIsOnAmount(int position) {
298 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
300 public void noteFocusIsOnComment(int position) {
301 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
303 public void toggleComment(int position) {
304 model.toggleComment(position);