]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
move high-level login out of the new transaction model to the adapter
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.java
index 45a57e542988dbcf9f485c9cf7d0f2652077ca66..3b6f2ecbc2861e90c54f5767604576613c37b696 100644 (file)
@@ -22,6 +22,7 @@ import android.os.Build;
 import android.text.Editable;
 import android.text.TextWatcher;
 import android.text.method.DigitsKeyListener;
+import android.view.Gravity;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.inputmethod.EditorInfo;
@@ -39,13 +40,16 @@ import androidx.recyclerview.widget.RecyclerView;
 
 import net.ktnx.mobileledger.R;
 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
+import net.ktnx.mobileledger.model.Currency;
 import net.ktnx.mobileledger.model.Data;
 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
 import net.ktnx.mobileledger.model.MobileLedgerProfile;
 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
 import net.ktnx.mobileledger.ui.DatePickerFragment;
+import net.ktnx.mobileledger.ui.OnCurrencySelectedListener;
 import net.ktnx.mobileledger.ui.TextViewClearHelper;
 import net.ktnx.mobileledger.utils.Colors;
+import net.ktnx.mobileledger.utils.DimensionUtils;
 import net.ktnx.mobileledger.utils.Logger;
 import net.ktnx.mobileledger.utils.MLDB;
 import net.ktnx.mobileledger.utils.Misc;
@@ -59,9 +63,11 @@ import java.util.Locale;
 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
 
 class NewTransactionItemHolder extends RecyclerView.ViewHolder
-        implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
+        implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback,
+        OnCurrencySelectedListener {
     private final String decimalSeparator;
     private final String decimalDot;
+    private final TextView tvCurrency;
     private NewTransactionModel.Item item;
     private TextView tvDate;
     private AutoCompleteTextView tvDescription;
@@ -81,16 +87,25 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
     private Observer<Boolean> editableObserver;
     private Observer<Boolean> commentVisibleObserver;
     private Observer<String> commentObserver;
+    private Observer<Currency.Position> currencyPositionObserver;
+    private Observer<Boolean> currencyGapObserver;
+    private Observer<Locale> localeObserver;
+    private Observer<Currency> currencyObserver;
+    private Observer<Boolean> showCurrencyObserver;
     private boolean inUpdate = false;
     private boolean syncingData = false;
     private View commentButton;
+    private NewTransactionItemsAdapter adapter;
+    //TODO multiple amounts with different currencies per posting
     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
         super(itemView);
+        this.adapter = adapter;
         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
         tvComment = itemView.findViewById(R.id.comment);
         new TextViewClearHelper().attachToTextView((EditText) tvComment);
         commentButton = itemView.findViewById(R.id.comment_button);
         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
+        tvCurrency = itemView.findViewById(R.id.currency);
         tvDate = itemView.findViewById(R.id.new_transaction_date);
         tvDescription = itemView.findViewById(R.id.new_transaction_description);
         lHead = itemView.findViewById(R.id.ntr_data);
@@ -170,18 +185,19 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                 syncData();
                 Logger.debug("textWatcher",
                         "syncData() returned, checking if transaction is submittable");
-                adapter.model.checkTransactionSubmittable(adapter);
+                adapter.checkTransactionSubmittable();
                 Logger.debug("textWatcher", "done");
             }
         };
         final TextWatcher amountWatcher = new TextWatcher() {
             @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+                Logger.debug("num",
+                        String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
+                                start, count, after));
             }
             @Override
-            public void onTextChanged(CharSequence s, int start, int before, int count) {
-
-            }
+            public void onTextChanged(CharSequence s, int start, int before, int count) {}
             @Override
             public void afterTextChanged(Editable s) {
                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@@ -189,16 +205,17 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                     // plus and minus are allowed only at the beginning
                     String allowed = "0123456789";
                     String val = s.toString();
+                    Logger.debug("input", val);
                     if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
                         allowed += "-";
                     if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
                         allowed += decimalSeparator + decimalDot;
 
                     tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
-
-                    syncData();
-                    adapter.model.checkTransactionSubmittable(adapter);
                 }
+
+                if (syncData())
+                    adapter.checkTransactionSubmittable();
             }
         };
         tvDescription.addTextChangedListener(tw);
@@ -206,9 +223,17 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
         tvComment.addTextChangedListener(tw);
         tvAmount.addTextChangedListener(amountWatcher);
 
-        // FIXME: react on locale changes
+        tvCurrency.setOnClickListener(v -> {
+            CurrencySelectorFragment cpf = new CurrencySelectorFragment();
+            cpf.setOnCurrencySelectedListener(this);
+            cpf.showPositionAndPadding();
+            final AppCompatActivity activity = (AppCompatActivity) v.getContext();
+            cpf.show(activity.getSupportFragmentManager(), "currency-selector");
+        });
+
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
-            tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
+            tvAmount.setKeyListener(
+                    DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
         else
             tvAmount.setKeyListener(
                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
@@ -314,6 +339,92 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
             else
                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
         };
+
+        localeObserver = locale -> {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
+                tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
+        };
+
+        currencyObserver = currency -> {
+            setCurrency(currency);
+            adapter.checkTransactionSubmittable();
+        };
+
+        currencyGapObserver = hasGap -> {
+            updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(), hasGap);
+        };
+
+        currencyPositionObserver = position -> {
+            updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
+        };
+
+        showCurrencyObserver = showCurrency -> {
+            if (showCurrency) {
+                tvCurrency.setVisibility(View.VISIBLE);
+            }
+            else {
+                tvCurrency.setVisibility(View.GONE);
+                item.setCurrency(null);
+            }
+        };
+    }
+    private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
+        ConstraintLayout.LayoutParams amountLP =
+                (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
+        ConstraintLayout.LayoutParams currencyLP =
+                (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
+
+        if (position == Currency.Position.before) {
+            currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
+            currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
+
+            amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
+            amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.startToEnd = tvCurrency.getId();
+
+            tvCurrency.setGravity(Gravity.END);
+        }
+        else {
+            currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
+            currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
+
+            amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
+            amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.endToStart = tvCurrency.getId();
+
+            tvCurrency.setGravity(Gravity.START);
+        }
+
+        amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
+        currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
+
+        tvAmount.setLayoutParams(amountLP);
+        tvCurrency.setLayoutParams(currencyLP);
+
+        // distance between the amount and the currency symbol
+        int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
+
+        if (position == Currency.Position.before) {
+            tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
+        }
+        else {
+            tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
+        }
+    }
+    private void setCurrencyString(String currency) {
+        if ((currency == null) || currency.isEmpty()) {
+            tvCurrency.setText(R.string.currency_symbol);
+            tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
+        }
+        else {
+            tvCurrency.setText(currency);
+            tvCurrency.setTextColor(Colors.defaultTextColor);
+        }
+    }
+    private void setCurrency(Currency currency) {
+        setCurrencyString((currency == null) ? null : currency.getName());
     }
     private void setEditable(Boolean editable) {
         tvDate.setEnabled(editable);
@@ -362,14 +473,16 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
      * syncData()
      * <p>
      * Stores the data from the UI elements into the model item
+     * Returns true if there were changes made that suggest transaction has to be
+     * checked for being submittable
      */
-    private void syncData() {
+    private boolean syncData() {
         if (item == null)
-            return;
+            return false;
 
         if (syncingData) {
             Logger.debug("new-trans", "skipping syncData() loop");
-            return;
+            return false;
         }
 
         syncingData = true;
@@ -386,12 +499,12 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
 
                     item.setComment(String.valueOf(tvComment.getText()));
 
-                    // TODO: handle multiple amounts
                     String amount = String.valueOf(tvAmount.getText());
                     amount = amount.trim();
 
                     if (amount.isEmpty()) {
                         account.resetAmount();
+//                        account.setCurrency(null);
                     }
                     else {
                         try {
@@ -404,12 +517,22 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                                     "input was '%s'", amount));
                             account.resetAmount();
                         }
+                        final String curr = String.valueOf(tvCurrency.getText());
+                        if (curr.equals(tvCurrency.getContext()
+                                                  .getResources()
+                                                  .getString(R.string.currency_symbol)) ||
+                            curr.isEmpty())
+                            account.setCurrency(null);
+                        else
+                            account.setCurrency(curr);
                     }
 
                     break;
                 case bottomFiller:
                     throw new RuntimeException("Should not happen");
             }
+
+            return true;
         }
         finally {
             syncingData = false;
@@ -442,6 +565,11 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                          .stopObservingFocusedItem(focusedAccountObserver);
                 this.item.getModel()
                          .stopObservingAccountCount(accountCountObserver);
+                Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
+                Data.currencyGap.removeObserver(currencyGapObserver);
+                Data.locale.removeObserver(localeObserver);
+                this.item.stopObservingCurrency(currencyObserver);
+                this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
 
                 this.item = null;
             }
@@ -467,6 +595,7 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
 //                        tvAmount.setHint(R.string.zero_amount);
                     }
                     tvAmount.setHint(item.getAmountHint());
+                    setCurrencyString(acc.getCurrency());
                     lHead.setVisibility(View.GONE);
                     lAccount.setVisibility(View.VISIBLE);
                     lPadding.setVisibility(View.GONE);
@@ -479,21 +608,34 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                     setEditable(false);
                     break;
             }
-
             if (this.item == null) { // was null or has changed
                 this.item = item;
                 final NewTransactionActivity activity =
                         (NewTransactionActivity) tvDescription.getContext();
-                item.observeDate(activity, dateObserver);
-                item.observeDescription(activity, descriptionObserver);
-                item.observeAmountHint(activity, hintObserver);
-                item.observeEditableFlag(activity, editableObserver);
-                item.observeCommentVisible(activity, commentVisibleObserver);
-                item.observeComment(activity, commentObserver);
-                item.getModel()
-                    .observeFocusedItem(activity, focusedAccountObserver);
-                item.getModel()
-                    .observeAccountCount(activity, accountCountObserver);
+
+                if (!item.isOfType(ItemType.bottomFiller)) {
+                    item.observeEditableFlag(activity, editableObserver);
+                    item.getModel()
+                        .observeFocusedItem(activity, focusedAccountObserver);
+                }
+                switch (item.getType()) {
+                    case generalData:
+                        item.observeDate(activity, dateObserver);
+                        item.observeDescription(activity, descriptionObserver);
+                        break;
+                    case transactionRow:
+                        item.observeAmountHint(activity, hintObserver);
+                        item.observeCommentVisible(activity, commentVisibleObserver);
+                        item.observeComment(activity, commentObserver);
+                        Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
+                        Data.currencyGap.observe(activity, currencyGapObserver);
+                        Data.locale.observe(activity, localeObserver);
+                        item.observeCurrency(activity, currencyObserver);
+                        item.getModel().showCurrency.observe(activity, showCurrencyObserver);
+                        item.getModel()
+                            .observeAccountCount(activity, accountCountObserver);
+                        break;
+                }
             }
         }
         finally {
@@ -511,6 +653,10 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
 
     }
     @Override
+    public void onCurrencySelected(Currency currency) {
+        adapter.model.setItemCurrency(this.item, currency, adapter);
+    }
+    @Override
     public void descriptionSelected(String description) {
         tvAccount.setText(description);
         tvAmount.requestFocus(View.FOCUS_FORWARD);