]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/templates/TemplateDetailsViewModel.java
Room-based profile management
[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 import net.ktnx.mobileledger.utils.Misc;
37
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Objects;
43 import java.util.concurrent.atomic.AtomicInteger;
44
45 public class TemplateDetailsViewModel extends ViewModel {
46     private final MutableLiveData<List<TemplateDetailsItem>> items =
47             new MutableLiveData<>(Collections.emptyList());
48     private final AtomicInteger syntheticItemId = new AtomicInteger(0);
49     private Long mPatternId;
50     private String mDefaultTemplateName;
51     private boolean itemsLoaded = false;
52     public String getDefaultTemplateName() {
53         return mDefaultTemplateName;
54     }
55     public void setDefaultTemplateName(String name) {
56         mDefaultTemplateName = name;
57     }
58
59     public void resetItems() {
60         applyList(new ArrayList<>());
61     }
62     public void applyList(List<TemplateDetailsItem> srcList) {
63         applyList(srcList, false);
64     }
65     public void applyList(List<TemplateDetailsItem> srcList, boolean async) {
66         boolean changes;
67         if (srcList == null) {
68             srcList = new ArrayList<>(items.getValue());
69             changes = false;
70         }
71         else
72             changes = true;
73
74         srcList = Collections.unmodifiableList(srcList);
75
76         {
77             Logger.debug("tmpl", "Considering old list");
78             for (TemplateDetailsItem item : srcList)
79                 Logger.debug("tmpl", String.format(Locale.US, " id %d pos %d", item.getId(),
80                         item.getPosition()));
81         }
82
83         ArrayList<TemplateDetailsItem> newList = new ArrayList<>();
84
85         boolean hasEmptyItem = false;
86
87         if (srcList.size() < 1) {
88             final TemplateDetailsItem.Header header = TemplateDetailsItem.createHeader();
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             modelHeader.setName(Misc.trim(modelHeader.getName()));
215             if (modelHeader.getName().isEmpty())
216                 modelHeader.setName(getDefaultTemplateName());
217             TemplateHeaderDAO headerDAO = DB.get()
218                                             .getTemplateDAO();
219             TemplateHeader dbHeader = modelHeader.toDBO();
220             if (newPattern) {
221                 dbHeader.setId(0L);
222                 dbHeader.setId(mPatternId = headerDAO.insertSync(dbHeader));
223             }
224             else
225                 headerDAO.updateSync(dbHeader);
226
227             Logger.debug("pattern-db",
228                     String.format(Locale.US, "Stored pattern header %d, item=%s", dbHeader.getId(),
229                             modelHeader));
230
231
232             TemplateAccountDAO taDAO = DB.get()
233                                          .getTemplateAccountDAO();
234             taDAO.prepareForSave(mPatternId);
235             for (int i = 1; i < list.size(); i++) {
236                 final TemplateDetailsItem.AccountRow accRowItem = list.get(i)
237                                                                       .asAccountRowItem();
238                 TemplateAccount dbAccount = accRowItem.toDBO(dbHeader.getId());
239                 dbAccount.setTemplateId(mPatternId);
240                 dbAccount.setPosition(i);
241                 if (dbAccount.getId() < 0) {
242                     dbAccount.setId(0);
243                     dbAccount.setId(taDAO.insertSync(dbAccount));
244                 }
245                 else
246                     taDAO.updateSync(dbAccount);
247
248                 Logger.debug("pattern-db", String.format(Locale.US,
249                         "Stored pattern account %d, account=%s, comment=%s, neg=%s, item=%s",
250                         dbAccount.getId(), dbAccount.getAccountName(),
251                         dbAccount.getAccountComment(), dbAccount.getNegateAmount(), accRowItem));
252             }
253             taDAO.finishSave(mPatternId);
254         });
255     }
256     private ArrayList<TemplateDetailsItem> copyItems() {
257         List<TemplateDetailsItem> oldList = items.getValue();
258
259         if (oldList == null)
260             return new ArrayList<>();
261
262         ArrayList<TemplateDetailsItem> result = new ArrayList<>(oldList.size());
263
264         for (TemplateDetailsItem item : oldList) {
265             if (item instanceof TemplateDetailsItem.Header)
266                 result.add(new TemplateDetailsItem.Header(item.asHeaderItem()));
267             else if (item instanceof TemplateDetailsItem.AccountRow)
268                 result.add(new TemplateDetailsItem.AccountRow(item.asAccountRowItem()));
269             else
270                 throw new RuntimeException("Unexpected item " + item);
271         }
272
273         return result;
274     }
275     public void moveItem(int sourcePos, int targetPos) {
276         final List<TemplateDetailsItem> newList = copyItems();
277
278         if (BuildConfig.DEBUG) {
279             Logger.debug("drag", "Before move:");
280             for (int i = 1; i < newList.size(); i++) {
281                 final TemplateDetailsItem item = newList.get(i);
282                 Logger.debug("drag",
283                         String.format(Locale.US, "  %d: id %d, pos %d", i, item.getId(),
284                                 item.getPosition()));
285             }
286         }
287
288         {
289             TemplateDetailsItem item = newList.remove(sourcePos);
290             newList.add(targetPos, item);
291         }
292
293         // adjust affected items' positions
294         {
295             int startPos, endPos;
296             if (sourcePos < targetPos) {
297                 // moved down
298                 startPos = sourcePos;
299                 endPos = targetPos;
300             }
301             else {
302                 // moved up
303                 startPos = targetPos;
304                 endPos = sourcePos;
305             }
306
307             for (int i = startPos; i <= endPos; i++) {
308                 newList.get(i)
309                        .setPosition(i);
310             }
311         }
312
313         if (BuildConfig.DEBUG) {
314             Logger.debug("drag", "After move:");
315             for (int i = 1; i < newList.size(); i++) {
316                 final TemplateDetailsItem item = newList.get(i);
317                 Logger.debug("drag",
318                         String.format(Locale.US, "  %d: id %d, pos %d", i, item.getId(),
319                                 item.getPosition()));
320             }
321         }
322
323         items.setValue(newList);
324     }
325     public void removeItem(int position) {
326         Logger.debug("tmpl", "Removing item at position " + position);
327         ArrayList<TemplateDetailsItem> newList = copyItems();
328         newList.remove(position);
329         for (int i = position; i < newList.size(); i++)
330             newList.get(i)
331                    .setPosition(i);
332         applyList(newList);
333     }
334 }