]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
move previous transaction lookup progress bar to the fragment
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionFragment.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.content.Context;
21 import android.os.Bundle;
22 import android.renderscript.RSInvalidStateException;
23 import android.view.LayoutInflater;
24 import android.view.Menu;
25 import android.view.MenuInflater;
26 import android.view.MenuItem;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.widget.ProgressBar;
30
31 import androidx.annotation.NonNull;
32 import androidx.annotation.Nullable;
33 import androidx.fragment.app.Fragment;
34 import androidx.fragment.app.FragmentActivity;
35 import androidx.lifecycle.ViewModelProvider;
36 import androidx.recyclerview.widget.LinearLayoutManager;
37 import androidx.recyclerview.widget.RecyclerView;
38
39 import com.google.android.material.floatingactionbutton.FloatingActionButton;
40 import com.google.android.material.snackbar.Snackbar;
41
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerTransaction;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.utils.Logger;
48 import net.ktnx.mobileledger.utils.Misc;
49
50 import org.jetbrains.annotations.NotNull;
51
52 import java.util.Date;
53
54 /**
55  * A simple {@link Fragment} subclass.
56  * Activities that contain this fragment must implement the
57  * {@link OnNewTransactionFragmentInteractionListener} interface
58  * to handle interaction events.
59  */
60
61 // TODO: offer to undo account remove-on-swipe
62 // TODO: transaction-level comment
63
64 public class NewTransactionFragment extends Fragment {
65     private NewTransactionItemsAdapter listAdapter;
66     private NewTransactionModel viewModel;
67     private RecyclerView list;
68     private FloatingActionButton fab;
69     private OnNewTransactionFragmentInteractionListener mListener;
70     private MobileLedgerProfile mProfile;
71     public NewTransactionFragment() {
72         // Required empty public constructor
73         setHasOptionsMenu(true);
74     }
75     @Override
76     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
77         super.onCreateOptionsMenu(menu, inflater);
78         inflater.inflate(R.menu.new_transaction_fragment, menu);
79         menu.findItem(R.id.action_reset_new_transaction_activity)
80             .setOnMenuItemClickListener(item -> {
81                 listAdapter.reset();
82                 return true;
83             });
84         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
85         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
86             viewModel.toggleCurrencyVisible();
87             return true;
88         });
89         final FragmentActivity activity = getActivity();
90         if (activity != null)
91             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
92     }
93     @Override
94     public View onCreateView(LayoutInflater inflater, ViewGroup container,
95                              Bundle savedInstanceState) {
96         // Inflate the layout for this fragment
97         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
98     }
99
100     @Override
101     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
102         super.onActivityCreated(savedInstanceState);
103         FragmentActivity activity = getActivity();
104         if (activity == null)
105             throw new RSInvalidStateException(
106                     "getActivity() returned null within onActivityCreated()");
107
108         list = activity.findViewById(R.id.new_transaction_accounts);
109         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
110         viewModel.observeDataProfile(this);
111         mProfile = Data.profile.getValue();
112         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
113         list.setAdapter(listAdapter);
114         list.setLayoutManager(new LinearLayoutManager(activity));
115         Data.profile.observe(getViewLifecycleOwner(), profile -> {
116             mProfile = profile;
117             listAdapter.setProfile(profile);
118         });
119         listAdapter.notifyDataSetChanged();
120         viewModel.isSubmittable()
121                  .observe(getViewLifecycleOwner(), isSubmittable -> {
122                      if (isSubmittable) {
123                          if (fab != null) {
124                              fab.show();
125                              fab.setEnabled(true);
126                          }
127                      }
128                      else {
129                          if (fab != null) {
130                              fab.hide();
131                          }
132                      }
133                  });
134 //        viewModel.checkTransactionSubmittable(listAdapter);
135
136         fab = activity.findViewById(R.id.fab);
137         fab.setOnClickListener(v -> onFabPressed());
138
139         boolean keep = false;
140
141         Bundle args = getArguments();
142         if (args != null) {
143             String error = args.getString("error");
144             if (error != null) {
145                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
146                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
147                         .show();
148                 keep = true;
149             }
150         }
151
152         int focused = 0;
153         if (savedInstanceState != null) {
154             keep |= savedInstanceState.getBoolean("keep", true);
155             focused = savedInstanceState.getInt("focused", 0);
156         }
157
158         if (!keep)
159             viewModel.reset();
160         else {
161             viewModel.setFocusedItem(focused);
162         }
163
164         ProgressBar p = activity.findViewById(R.id.progressBar);
165         viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
166             if (isBusy) {
167 //                Handler h = new Handler();
168 //                h.postDelayed(() -> {
169 //                    if (viewModel.getBusyFlag())
170 //                        p.setVisibility(View.VISIBLE);
171 //
172 //                }, 10);
173                         p.setVisibility(View.VISIBLE);
174             }
175             else
176                 p.setVisibility(View.INVISIBLE);
177         });
178     }
179     @Override
180     public void onSaveInstanceState(@NonNull Bundle outState) {
181         super.onSaveInstanceState(outState);
182         outState.putBoolean("keep", true);
183         final int focusedItem = viewModel.getFocusedItem();
184         outState.putInt("focused", focusedItem);
185     }
186     private void onFabPressed() {
187         fab.setEnabled(false);
188         Misc.hideSoftKeyboard(this);
189         if (mListener != null) {
190             Date date = viewModel.getDate();
191             LedgerTransaction tr =
192                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
193
194             LedgerTransactionAccount emptyAmountAccount = null;
195             float emptyAmountAccountBalance = 0;
196             for (int i = 0; i < viewModel.getAccountCount(); i++) {
197                 LedgerTransactionAccount acc =
198                         new LedgerTransactionAccount(viewModel.getAccount(i));
199                 if (acc.getAccountName()
200                        .trim()
201                        .isEmpty())
202                     continue;
203
204                 if (acc.isAmountSet()) {
205                     emptyAmountAccountBalance += acc.getAmount();
206                 }
207                 else {
208                     emptyAmountAccount = acc;
209                 }
210
211                 tr.addAccount(acc);
212             }
213
214             if (emptyAmountAccount != null)
215                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
216
217             mListener.onTransactionSave(tr);
218         }
219     }
220
221     @Override
222     public void onAttach(@NotNull Context context) {
223         super.onAttach(context);
224         if (context instanceof OnNewTransactionFragmentInteractionListener) {
225             mListener = (OnNewTransactionFragmentInteractionListener) context;
226         }
227         else {
228             throw new RuntimeException(
229                     context.toString() + " must implement OnFragmentInteractionListener");
230         }
231     }
232
233     @Override
234     public void onDetach() {
235         super.onDetach();
236         mListener = null;
237     }
238
239     /**
240      * This interface must be implemented by activities that contain this
241      * fragment to allow an interaction in this fragment to be communicated
242      * to the activity and potentially other fragments contained in that
243      * activity.
244      * <p>
245      * See the Android Training lesson <a href=
246      * "http://developer.android.com/training/basics/fragments/communicating.html"
247      * >Communicating with Other Fragments</a> for more information.
248      */
249     public interface OnNewTransactionFragmentInteractionListener {
250         void onTransactionSave(LedgerTransaction tr);
251     }
252 }