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