]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
e9d2e33134aff3fabb19a60d12f47da06656290b
[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.ViewModelProviders;
34 import androidx.recyclerview.widget.ItemTouchHelper;
35 import androidx.recyclerview.widget.LinearLayoutManager;
36 import androidx.recyclerview.widget.RecyclerView;
37
38 import com.google.android.material.floatingactionbutton.FloatingActionButton;
39 import com.google.android.material.snackbar.Snackbar;
40
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerTransaction;
44 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
45 import net.ktnx.mobileledger.model.MobileLedgerProfile;
46 import net.ktnx.mobileledger.utils.Logger;
47 import net.ktnx.mobileledger.utils.Misc;
48
49 import org.jetbrains.annotations.NotNull;
50
51 import java.util.Date;
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 public class NewTransactionFragment extends Fragment {
60     private NewTransactionItemsAdapter listAdapter;
61     private NewTransactionModel viewModel;
62     private RecyclerView list;
63     private FloatingActionButton fab;
64     private OnNewTransactionFragmentInteractionListener mListener;
65     private MobileLedgerProfile mProfile;
66     public NewTransactionFragment() {
67         // Required empty public constructor
68         setHasOptionsMenu(true);
69     }
70     @Override
71     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
72         super.onCreateOptionsMenu(menu, inflater);
73         inflater.inflate(R.menu.new_transaction_fragment, menu);
74         menu.findItem(R.id.action_reset_new_transaction_activity)
75             .setOnMenuItemClickListener(item -> {
76                 listAdapter.reset();
77                 return true;
78             });
79     }
80     @Override
81     public View onCreateView(LayoutInflater inflater, ViewGroup container,
82                              Bundle savedInstanceState) {
83         // Inflate the layout for this fragment
84         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
85     }
86
87     @Override
88     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
89         super.onActivityCreated(savedInstanceState);
90         FragmentActivity activity = getActivity();
91         if (activity == null)
92             throw new RSInvalidStateException(
93                     "getActivity() returned null within onActivityCreated()");
94
95         list = activity.findViewById(R.id.new_transaction_accounts);
96         viewModel = ViewModelProviders.of(activity)
97                                       .get(NewTransactionModel.class);
98         mProfile = Data.profile.getValue();
99         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
100         list.setAdapter(listAdapter);
101         list.setLayoutManager(new LinearLayoutManager(activity));
102         Data.profile.observe(this, profile -> {
103             mProfile = profile;
104             listAdapter.setProfile(profile);
105         });
106         listAdapter.notifyDataSetChanged();
107         new ItemTouchHelper(new ItemTouchHelper.Callback() {
108             @Override
109             public int getMovementFlags(@NonNull RecyclerView recyclerView,
110                                         @NonNull RecyclerView.ViewHolder viewHolder) {
111                 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
112                 // the top item is always there (date and description)
113                 if (viewHolder.getAdapterPosition() > 0) {
114                     if (viewModel.getAccountCount() > 2) {
115                         flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
116                                 ItemTouchHelper.START | ItemTouchHelper.END);
117                     }
118                 }
119
120                 return flags;
121             }
122             @Override
123             public boolean onMove(@NonNull RecyclerView recyclerView,
124                                   @NonNull RecyclerView.ViewHolder viewHolder,
125                                   @NonNull RecyclerView.ViewHolder target) {
126                 return false;
127             }
128             @Override
129             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
130                 if (viewModel.getAccountCount() == 2)
131                     Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
132                             Snackbar.LENGTH_LONG)
133                             .setAction("Action", null)
134                             .show();
135                 else {
136                     int pos = viewHolder.getAdapterPosition();
137                     viewModel.removeItem(pos - 1);
138                     listAdapter.notifyItemRemoved(pos);
139                     viewModel.sendCountNotifications(); // needed after items re-arrangement
140                     viewModel.checkTransactionSubmittable(listAdapter);
141                 }
142             }
143         }).attachToRecyclerView(list);
144
145         viewModel.isSubmittable()
146                  .observe(this, isSubmittable -> {
147                      if (isSubmittable) {
148                          if (fab != null) {
149                              fab.show();
150                              fab.setEnabled(true);
151                          }
152                      }
153                      else {
154                          if (fab != null) {
155                              fab.hide();
156                          }
157                      }
158                  });
159         viewModel.checkTransactionSubmittable(listAdapter);
160
161         fab = activity.findViewById(R.id.fab);
162         fab.setOnClickListener(v -> onFabPressed());
163
164         boolean keep = false;
165
166         Bundle args = getArguments();
167         if (args != null) {
168             String error = args.getString("error");
169             if (error != null) {
170                 // TODO display error
171                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
172                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
173                         .show();
174                 keep = true;
175             }
176         }
177
178         int focused = 0;
179         if (savedInstanceState != null) {
180             keep |= savedInstanceState.getBoolean("keep", true);
181             focused = savedInstanceState.getInt("focused", 0);
182         }
183
184         if (!keep)
185             viewModel.reset();
186         else {
187             viewModel.setFocusedItem(focused);
188         }
189     }
190     @Override
191     public void onSaveInstanceState(@NonNull Bundle outState) {
192         super.onSaveInstanceState(outState);
193         outState.putBoolean("keep", true);
194         final int focusedItem = viewModel.getFocusedItem();
195         outState.putInt("focused", focusedItem);
196     }
197     private void onFabPressed() {
198         fab.setEnabled(false);
199         Misc.hideSoftKeyboard(this);
200         if (mListener != null) {
201             Date date = viewModel.getDate();
202             LedgerTransaction tr =
203                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
204
205             LedgerTransactionAccount emptyAmountAccount = null;
206             float emptyAmountAccountBalance = 0;
207             for (int i = 0; i < viewModel.getAccountCount(); i++) {
208                 LedgerTransactionAccount acc = viewModel.getAccount(i);
209                 if (acc.getAccountName()
210                        .trim()
211                        .isEmpty())
212                     continue;
213
214                 if (acc.isAmountSet()) {
215                     emptyAmountAccountBalance += acc.getAmount();
216                 }
217                 else {
218                     emptyAmountAccount = acc;
219                 }
220
221                 tr.addAccount(acc);
222             }
223
224             if (emptyAmountAccount != null)
225                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
226
227             mListener.onTransactionSave(tr);
228         }
229     }
230
231     @Override
232     public void onAttach(@NotNull Context context) {
233         super.onAttach(context);
234         if (context instanceof OnNewTransactionFragmentInteractionListener) {
235             mListener = (OnNewTransactionFragmentInteractionListener) context;
236         }
237         else {
238             throw new RuntimeException(
239                     context.toString() + " must implement OnFragmentInteractionListener");
240         }
241     }
242
243     @Override
244     public void onDetach() {
245         super.onDetach();
246         mListener = null;
247     }
248
249     /**
250      * This interface must be implemented by activities that contain this
251      * fragment to allow an interaction in this fragment to be communicated
252      * to the activity and potentially other fragments contained in that
253      * activity.
254      * <p>
255      * See the Android Training lesson <a href=
256      * "http://developer.android.com/training/basics/fragments/communicating.html"
257      * >Communicating with Other Fragments</a> for more information.
258      */
259     public interface OnNewTransactionFragmentInteractionListener {
260         void onTransactionSave(LedgerTransaction tr);
261     }
262 }