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;
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;
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;
54 public void setDefaultPatternName(String name) {
55 mDefaultPatternName = name;
58 public void resetItems() {
59 applyList(new ArrayList<>());
61 public void applyList(List<TemplateDetailsItem> srcList) {
62 applyList(srcList, false);
64 public void applyList(List<TemplateDetailsItem> srcList, boolean async) {
66 if (srcList == null) {
67 srcList = new ArrayList<>(items.getValue());
73 srcList = Collections.unmodifiableList(srcList);
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(),
82 ArrayList<TemplateDetailsItem> newList = new ArrayList<>();
84 boolean hasEmptyItem = false;
86 if (srcList.size() < 1) {
87 final TemplateDetailsItem.Header header = TemplateDetailsItem.createHeader();
88 header.setName(mDefaultPatternName);
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 TemplateHeaderDAO headerDAO = DB.get()
216 TemplateHeader dbHeader = modelHeader.toDBO();
218 dbHeader.setId(null);
219 dbHeader.setId(mPatternId = headerDAO.insertSync(dbHeader));
222 headerDAO.updateSync(dbHeader);
224 Logger.debug("pattern-db",
225 String.format(Locale.US, "Stored pattern header %d, item=%s", dbHeader.getId(),
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)
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));
243 taDAO.updateSync(dbAccount);
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));
250 taDAO.finishSave(mPatternId);
253 private ArrayList<TemplateDetailsItem> copyItems() {
254 List<TemplateDetailsItem> oldList = items.getValue();
255 ArrayList<TemplateDetailsItem> result = new ArrayList<>(oldList.size());
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()));
263 throw new RuntimeException("Unexpected item " + item);
268 public void moveItem(int sourcePos, int targetPos) {
269 final List<TemplateDetailsItem> newList = copyItems();
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);
276 String.format(Locale.US, " %d: id %d, pos %d", i, item.getId(),
277 item.getPosition()));
282 TemplateDetailsItem item = newList.remove(sourcePos);
283 newList.add(targetPos, item);
286 // adjust affected items' positions
288 int startPos, endPos;
289 if (sourcePos < targetPos) {
291 startPos = sourcePos;
296 startPos = targetPos;
300 for (int i = startPos; i <= endPos; i++) {
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);
311 String.format(Locale.US, " %d: id %d, pos %d", i, item.getId(),
312 item.getPosition()));
316 items.setValue(newList);
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++)