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