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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.templates;
20 import android.os.AsyncTask;
22 import androidx.lifecycle.LiveData;
23 import androidx.lifecycle.MutableLiveData;
24 import androidx.lifecycle.Observer;
25 import androidx.lifecycle.ViewModel;
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;
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;
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;
55 public void setDefaultTemplateName(String name) {
56 mDefaultTemplateName = name;
59 public void resetItems() {
60 applyList(new ArrayList<>());
62 public void applyList(List<TemplateDetailsItem> srcList) {
63 applyList(srcList, false);
65 public void applyList(List<TemplateDetailsItem> srcList, boolean async) {
67 if (srcList == null) {
68 srcList = new ArrayList<>(items.getValue());
74 srcList = Collections.unmodifiableList(srcList);
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(),
83 ArrayList<TemplateDetailsItem> newList = new ArrayList<>();
85 boolean hasEmptyItem = false;
87 if (srcList.size() < 1) {
88 final TemplateDetailsItem.Header header = TemplateDetailsItem.createHeader();
94 newList.add(srcList.get(0));
97 for (int i = 1; i < srcList.size(); i++) {
98 final TemplateDetailsItem.AccountRow accRow = srcList.get(i)
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());
108 changes = true; // row skipped
113 accRow.setPosition(newList.size());
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);
129 final TemplateDetailsItem.AccountRow accountRow =
130 TemplateDetailsItem.createAccountRow();
131 accountRow.setId(genItemId());
132 accountRow.setPosition(newList.size());
133 newList.add(accountRow);
138 Logger.debug("tmpl", "Changes detected, applying new list");
141 items.postValue(newList);
143 items.setValue(newList);
146 Logger.debug("tmpl", "No changes, ignoring new list");
148 public int genItemId() {
149 return syntheticItemId.decrementAndGet();
151 public LiveData<List<TemplateDetailsItem>> getItems(Long patternId) {
152 if (itemsLoaded && Objects.equals(patternId, this.mPatternId))
155 if (patternId != null && patternId <= 0)
156 throw new IllegalArgumentException("Pattern ID " + patternId + " is invalid");
158 mPatternId = patternId;
160 if (mPatternId == null) {
167 LiveData<TemplateWithAccounts> dbList = db.getTemplateDAO()
168 .getTemplateWithAccounts(mPatternId);
169 Observer<TemplateWithAccounts> observer = new Observer<TemplateWithAccounts>() {
171 public void onChanged(TemplateWithAccounts src) {
172 ArrayList<TemplateDetailsItem> l = new ArrayList<>();
174 TemplateDetailsItem header = TemplateDetailsItem.fromRoomObject(src.header);
175 Logger.debug("tmpl-db", "Got header template item with id of " + header.getId());
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));
183 for (TemplateDetailsItem i : l) {
184 Logger.debug("tmpl-db", "Loaded pattern item " + i);
189 dbList.removeObserver(this);
192 dbList.observeForever(observer);
196 public void setTestText(String text) {
197 List<TemplateDetailsItem> list = new ArrayList<>(items.getValue());
198 TemplateDetailsItem.Header header = new TemplateDetailsItem.Header(list.get(0)
200 header.setTestText(text);
203 items.setValue(list);
205 public void onSaveTemplate() {
206 Logger.debug("flow", "PatternDetailsViewModel.onSavePattern(); model=" + this);
207 final List<TemplateDetailsItem> list = Objects.requireNonNull(items.getValue());
209 AsyncTask.execute(() -> {
210 boolean newPattern = mPatternId == null || mPatternId <= 0;
212 TemplateDetailsItem.Header modelHeader = list.get(0)
214 modelHeader.setName(Misc.trim(modelHeader.getName()));
215 if (modelHeader.getName().isEmpty())
216 modelHeader.setName(getDefaultTemplateName());
217 TemplateHeaderDAO headerDAO = DB.get()
219 TemplateHeader dbHeader = modelHeader.toDBO();
222 dbHeader.setId(mPatternId = headerDAO.insertSync(dbHeader));
225 headerDAO.updateSync(dbHeader);
227 Logger.debug("pattern-db",
228 String.format(Locale.US, "Stored pattern header %d, item=%s", dbHeader.getId(),
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)
238 TemplateAccount dbAccount = accRowItem.toDBO(dbHeader.getId());
239 dbAccount.setTemplateId(mPatternId);
240 dbAccount.setPosition(i);
241 if (dbAccount.getId() < 0) {
243 dbAccount.setId(taDAO.insertSync(dbAccount));
246 taDAO.updateSync(dbAccount);
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));
253 taDAO.finishSave(mPatternId);
256 private ArrayList<TemplateDetailsItem> copyItems() {
257 List<TemplateDetailsItem> oldList = items.getValue();
260 return new ArrayList<>();
262 ArrayList<TemplateDetailsItem> result = new ArrayList<>(oldList.size());
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()));
270 throw new RuntimeException("Unexpected item " + item);
275 public void moveItem(int sourcePos, int targetPos) {
276 final List<TemplateDetailsItem> newList = copyItems();
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);
283 String.format(Locale.US, " %d: id %d, pos %d", i, item.getId(),
284 item.getPosition()));
289 TemplateDetailsItem item = newList.remove(sourcePos);
290 newList.add(targetPos, item);
293 // adjust affected items' positions
295 int startPos, endPos;
296 if (sourcePos < targetPos) {
298 startPos = sourcePos;
303 startPos = targetPos;
307 for (int i = startPos; i <= endPos; i++) {
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);
318 String.format(Locale.US, " %d: id %d, pos %d", i, item.getId(),
319 item.getPosition()));
323 items.setValue(newList);
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++)