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