]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/templates/TemplateDetailsViewModel.java
fixup: template details help
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / templates / TemplateDetailsViewModel.java
1 /*
2  * Copyright © 2021 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.templates;
19
20 import android.os.AsyncTask;
21
22 import androidx.lifecycle.LiveData;
23 import androidx.lifecycle.MutableLiveData;
24 import androidx.lifecycle.Observer;
25 import androidx.lifecycle.ViewModel;
26
27 import net.ktnx.mobileledger.BuildConfig;
28 import net.ktnx.mobileledger.dao.TemplateAccountDAO;
29 import net.ktnx.mobileledger.dao.TemplateHeaderDAO;
30 import net.ktnx.mobileledger.db.DB;
31 import net.ktnx.mobileledger.db.TemplateAccount;
32 import net.ktnx.mobileledger.db.TemplateHeader;
33 import net.ktnx.mobileledger.db.TemplateWithAccounts;
34 import net.ktnx.mobileledger.model.TemplateDetailsItem;
35 import net.ktnx.mobileledger.utils.Logger;
36
37 import java.util.ArrayList;
38 import java.util.Collections;
39 import java.util.List;
40 import java.util.Locale;
41 import java.util.Objects;
42 import java.util.concurrent.atomic.AtomicInteger;
43
44 public class TemplateDetailsViewModel extends ViewModel {
45     private final MutableLiveData<List<TemplateDetailsItem>> items =
46             new MutableLiveData<>(Collections.emptyList());
47     private final AtomicInteger syntheticItemId = new AtomicInteger(0);
48     private Long mPatternId;
49     private String mDefaultPatternName;
50     private boolean itemsLoaded = false;
51     public String getDefaultPatternName() {
52         return mDefaultPatternName;
53     }
54     public void setDefaultPatternName(String name) {
55         mDefaultPatternName = name;
56     }
57
58     public void resetItems() {
59         applyList(new ArrayList<>());
60     }
61     public void applyList(List<TemplateDetailsItem> srcList) {
62         applyList(srcList, false);
63     }
64     public void applyList(List<TemplateDetailsItem> srcList, boolean async) {
65         boolean changes;
66         if (srcList == null) {
67             srcList = new ArrayList<>(items.getValue());
68             changes = false;
69         }
70         else
71             changes = true;
72
73         srcList = Collections.unmodifiableList(srcList);
74
75         {
76             Logger.debug("tmpl", "Considering old list");
77             for (TemplateDetailsItem item : srcList)
78                 Logger.debug("tmpl", String.format(Locale.US, " id %d pos %d", item.getId(),
79                         item.getPosition()));
80         }
81
82         ArrayList<TemplateDetailsItem> newList = new ArrayList<>();
83
84         boolean hasEmptyItem = false;
85
86         if (srcList.size() < 1) {
87             final TemplateDetailsItem.Header header = TemplateDetailsItem.createHeader();
88             header.setName(mDefaultPatternName);
89             header.setId(0);
90             newList.add(header);
91             changes = true;
92         }
93         else {
94             newList.add(srcList.get(0));
95         }
96
97         for (int i = 1; i < srcList.size(); i++) {
98             final TemplateDetailsItem.AccountRow accRow = srcList.get(i)
99                                                                  .asAccountRowItem();
100             if (accRow.isEmpty()) {
101                 // it is normal to have two empty rows if they are at the
102                 // top (position 1 and 2)
103                 if (!hasEmptyItem || i < 3) {
104                     accRow.setPosition(newList.size());
105                     newList.add(accRow);
106                 }
107                 else
108                     changes = true; // row skipped
109
110                 hasEmptyItem = true;
111             }
112             else {
113                 accRow.setPosition(newList.size());
114                 newList.add(accRow);
115             }
116         }
117
118         while (newList.size() < 3) {
119             final TemplateDetailsItem.AccountRow accountRow =
120                     TemplateDetailsItem.createAccountRow();
121             accountRow.setId(genItemId());
122             accountRow.setPosition(newList.size());
123             newList.add(accountRow);
124             changes = true;
125             hasEmptyItem = true;
126         }
127
128         if (!hasEmptyItem) {
129             final TemplateDetailsItem.AccountRow accountRow =
130                     TemplateDetailsItem.createAccountRow();
131             accountRow.setId(genItemId());
132             accountRow.setPosition(newList.size());
133             newList.add(accountRow);
134             changes = true;
135         }
136
137         if (changes) {
138             Logger.debug("tmpl", "Changes detected, applying new list");
139
140             if (async)
141                 items.postValue(newList);
142             else
143                 items.setValue(newList);
144         }
145         else
146             Logger.debug("tmpl", "No changes, ignoring new list");
147     }
148     public int genItemId() {
149         return syntheticItemId.decrementAndGet();
150     }
151     public LiveData<List<TemplateDetailsItem>> getItems(Long patternId) {
152         if (itemsLoaded && Objects.equals(patternId, this.mPatternId))
153             return items;
154
155         if (patternId != null && patternId <= 0)
156             throw new IllegalArgumentException("Pattern ID " + patternId + " is invalid");
157
158         mPatternId = patternId;
159
160         if (mPatternId == null) {
161             resetItems();
162             itemsLoaded = true;
163             return items;
164         }
165
166         DB db = DB.get();
167         LiveData<TemplateWithAccounts> dbList = db.getTemplateDAO()
168                                                   .getTemplateWithAccounts(mPatternId);
169         Observer<TemplateWithAccounts> observer = new Observer<TemplateWithAccounts>() {
170             @Override
171             public void onChanged(TemplateWithAccounts src) {
172                 ArrayList<TemplateDetailsItem> l = new ArrayList<>();
173
174                 TemplateDetailsItem header = TemplateDetailsItem.fromRoomObject(src.header);
175                 Logger.debug("tmpl-db", "Got header template item with id of " + header.getId());
176                 l.add(header);
177                 Collections.sort(src.accounts,
178                         (o1, o2) -> Long.compare(o1.getPosition(), o2.getPosition()));
179                 for (TemplateAccount acc : src.accounts) {
180                     l.add(TemplateDetailsItem.fromRoomObject(acc));
181                 }
182
183                 for (TemplateDetailsItem i : l) {
184                     Logger.debug("tmpl-db", "Loaded pattern item " + i);
185                 }
186                 applyList(l, true);
187                 itemsLoaded = true;
188
189                 dbList.removeObserver(this);
190             }
191         };
192         dbList.observeForever(observer);
193
194         return items;
195     }
196     public void setTestText(String text) {
197         List<TemplateDetailsItem> list = new ArrayList<>(items.getValue());
198         TemplateDetailsItem.Header header = new TemplateDetailsItem.Header(list.get(0)
199                                                                                .asHeaderItem());
200         header.setTestText(text);
201         list.set(0, header);
202
203         items.setValue(list);
204     }
205     public void onSaveTemplate() {
206         Logger.debug("flow", "PatternDetailsViewModel.onSavePattern(); model=" + this);
207         final List<TemplateDetailsItem> list = Objects.requireNonNull(items.getValue());
208
209         AsyncTask.execute(() -> {
210             boolean newPattern = mPatternId == null || mPatternId <= 0;
211
212             TemplateDetailsItem.Header modelHeader = list.get(0)
213                                                          .asHeaderItem();
214             TemplateHeaderDAO headerDAO = DB.get()
215                                             .getTemplateDAO();
216             TemplateHeader dbHeader = modelHeader.toDBO();
217             if (newPattern) {
218                 dbHeader.setId(null);
219                 dbHeader.setId(mPatternId = headerDAO.insertSync(dbHeader));
220             }
221             else
222                 headerDAO.updateSync(dbHeader);
223
224             Logger.debug("pattern-db",
225                     String.format(Locale.US, "Stored pattern header %d, item=%s", dbHeader.getId(),
226                             modelHeader));
227
228
229             TemplateAccountDAO taDAO = DB.get()
230                                          .getTemplateAccountDAO();
231             taDAO.prepareForSave(mPatternId);
232             for (int i = 1; i < list.size(); i++) {
233                 final TemplateDetailsItem.AccountRow accRowItem = list.get(i)
234                                                                       .asAccountRowItem();
235                 TemplateAccount dbAccount = accRowItem.toDBO(dbHeader.getId());
236                 dbAccount.setTemplateId(mPatternId);
237                 dbAccount.setPosition(i);
238                 if (dbAccount.getId() < 0) {
239                     dbAccount.setId(null);
240                     dbAccount.setId(taDAO.insertSync(dbAccount));
241                 }
242                 else
243                     taDAO.updateSync(dbAccount);
244
245                 Logger.debug("pattern-db", String.format(Locale.US,
246                         "Stored pattern account %d, account=%s, comment=%s, neg=%s, item=%s",
247                         dbAccount.getId(), dbAccount.getAccountName(),
248                         dbAccount.getAccountComment(), dbAccount.getNegateAmount(), accRowItem));
249             }
250             taDAO.finishSave(mPatternId);
251         });
252     }
253     private ArrayList<TemplateDetailsItem> copyItems() {
254         List<TemplateDetailsItem> oldList = items.getValue();
255         ArrayList<TemplateDetailsItem> result = new ArrayList<>(oldList.size());
256
257         for (TemplateDetailsItem item : oldList) {
258             if (item instanceof TemplateDetailsItem.Header)
259                 result.add(new TemplateDetailsItem.Header(item.asHeaderItem()));
260             else if (item instanceof TemplateDetailsItem.AccountRow)
261                 result.add(new TemplateDetailsItem.AccountRow(item.asAccountRowItem()));
262             else
263                 throw new RuntimeException("Unexpected item " + item);
264         }
265
266         return result;
267     }
268     public void moveItem(int sourcePos, int targetPos) {
269         final List<TemplateDetailsItem> newList = copyItems();
270
271         if (BuildConfig.DEBUG) {
272             Logger.debug("drag", "Before move:");
273             for (int i = 1; i < newList.size(); i++) {
274                 final TemplateDetailsItem item = newList.get(i);
275                 Logger.debug("drag",
276                         String.format(Locale.US, "  %d: id %d, pos %d", i, item.getId(),
277                                 item.getPosition()));
278             }
279         }
280
281         {
282             TemplateDetailsItem item = newList.remove(sourcePos);
283             newList.add(targetPos, item);
284         }
285
286         // adjust affected items' positions
287         {
288             int startPos, endPos;
289             if (sourcePos < targetPos) {
290                 // moved down
291                 startPos = sourcePos;
292                 endPos = targetPos;
293             }
294             else {
295                 // moved up
296                 startPos = targetPos;
297                 endPos = sourcePos;
298             }
299
300             for (int i = startPos; i <= endPos; i++) {
301                 newList.get(i)
302                        .setPosition(i);
303             }
304         }
305
306         if (BuildConfig.DEBUG) {
307             Logger.debug("drag", "After move:");
308             for (int i = 1; i < newList.size(); i++) {
309                 final TemplateDetailsItem item = newList.get(i);
310                 Logger.debug("drag",
311                         String.format(Locale.US, "  %d: id %d, pos %d", i, item.getId(),
312                                 item.getPosition()));
313             }
314         }
315
316         items.setValue(newList);
317     }
318     public void removeItem(int position) {
319         Logger.debug("tmpl", "Removing item at position " + position);
320         ArrayList<TemplateDetailsItem> newList = copyItems();
321         newList.remove(position);
322         for (int i = position; i < newList.size(); i++)
323             newList.get(i)
324                    .setPosition(i);
325         applyList(newList);
326     }
327 }