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