TransactionsViewModel
unknown
swift
2 years ago
3.3 kB
3
Indexable
Never
import UIKit import SkeletonView class TransactionsViewModel { private weak var viewController: TransactionHistoryViewController? private var networkManager: NetworkManagerType { NetworkManager.shared } private(set) var isLoading = false lazy var fromDate = toDate.addingTimeInterval(-3600 * 24 * 7) lazy var toDate = Date() private(set) var transactions: [Transaction]? { didSet { viewController?.tableView.backgroundLabelText = (transactions?.isEmpty ?? true) ? NSLocalizedString("NoOperationsForFilters") : nil viewController?.view.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.25)) viewController?.tableView.reloadData() } } private var offset: Int = 0 var filter: String? { didSet { transactions = nil offset = 0 getTransactions() } } init(view: TransactionHistoryViewController) { self.viewController = view } func getTransactions(completion: (() -> ())? = nil) { isLoading = true networkManager.transactions(from: fromDate, to: toDate, pageSize: 50, offset: offset) { [weak self] (result) in self?.isLoading = false DispatchQueue.main.async { switch result { case .success(let transactions): if self?.transactions == nil { self?.onNilTransactions(transactions) } else { self?.onNotNilTransactions(transactions) } case .failure: self?.viewController?.tableView.backgroundLabelText = NSLocalizedString("Operation Failed. Try again.") self?.viewController?.view.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.25)) } } completion?() } } private func onNilTransactions(_ transactions: [Transaction]?) { guard let transactions = transactions else { self.viewController?.tableView.backgroundLabelText = NSLocalizedString("NoOperationsForFilters") self.viewController?.view.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.25)) return } offset = transactions.count self.transactions = filter == nil ? getNAOperationTypeFilters(transactions) : getAllOperationTypeFilters(transactions) } private func onNotNilTransactions(_ transactions: [Transaction]?) { guard let transactions = transactions else { return } offset += transactions.count self.transactions?.append(contentsOf: filter == nil ? getNAOperationTypeFilters(transactions) : getAllOperationTypeFilters(transactions)) } private func getNAOperationTypeFilters(_ transactions: [Transaction]) -> [Transaction] { return transactions.filter { $0.typeOfOperation != "NA" } } private func getAllOperationTypeFilters(_ transactions: [Transaction]) -> [Transaction] { return transactions.filter { $0.typeOfOperation != "NA" && $0.typeOfOperation == filter } } func clearTransactions() { transactions = nil offset = 0 } }