101 lines
3.0 KiB
Swift
101 lines
3.0 KiB
Swift
//
|
|
// AccountServiceResources.swift
|
|
// Wallet
|
|
//
|
|
// Created by Igor on 05.03.2021.
|
|
// Copyright © 2021 AM. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import WalletFoundation
|
|
import WalletKit
|
|
|
|
private let freeKey = CommonKey("Account.Service.Resources.free")
|
|
private let paidKey = CommonKey("Account.Service.Resources.paid")
|
|
private let isEnabledKey = CommonKey("Account.Service.Resources.isEnabled")
|
|
|
|
extension Notification.Name {
|
|
static let didUpdateAccountQuota = Self("Account.Service.Resources.didUpdateAccountQuota")
|
|
}
|
|
|
|
extension Account.Service {
|
|
final class CommonResources {
|
|
|
|
private var service: Resources.Service.Quota?
|
|
|
|
private(set) var free: Int {
|
|
get { Settings.shared[freeKey] }
|
|
set { Settings.shared[freeKey] = newValue }
|
|
}
|
|
|
|
private(set) var paid: Int {
|
|
get { Settings.shared[paidKey] }
|
|
set { Settings.shared[paidKey] = newValue }
|
|
}
|
|
|
|
var count: Int { self.free + self.paid }
|
|
|
|
var isEmpty: Bool { !self.service.isExist && self.free == 0 && self.paid == 0 }
|
|
|
|
var isEnabled: Bool {
|
|
get { Settings.shared[isEnabledKey] }
|
|
set {
|
|
Settings.shared[isEnabledKey] = newValue
|
|
Notification.post(name: .didUpdateAccountQuota)
|
|
}
|
|
}
|
|
|
|
init() {
|
|
if !Settings.shared.contains(isEnabledKey) {
|
|
self.isEnabled = true
|
|
}
|
|
}
|
|
|
|
func update(free: Int, paid: Int) {
|
|
self.free = free
|
|
self.paid = paid
|
|
Notification.post(name: .didUpdateAccountQuota)
|
|
|
|
}
|
|
|
|
func fetch(using account: WalletKit.Wallet?, clear: Bool = false, force: Bool = false) {
|
|
if clear {
|
|
self.paid = 0
|
|
self.free = 0
|
|
self.service = nil
|
|
Notification.post(name: .didUpdateAccountQuota)
|
|
}
|
|
|
|
guard let account, !account.name.isEmpty else { return }
|
|
|
|
self.perform(using: account)
|
|
if force {
|
|
delayed(4) { self.perform(using: account) }
|
|
delayed(8) { self.perform(using: account) }
|
|
delayed(16) { self.perform(using: account) }
|
|
}
|
|
}
|
|
|
|
private func perform(using account: WalletKit.Wallet) {
|
|
|
|
if let service = self.service {
|
|
if service.account != account.name {
|
|
self.service = .init(account: account.name)
|
|
}
|
|
} else {
|
|
self.service = .init(account: account.name)
|
|
}
|
|
|
|
self.service >>- { service in
|
|
service.fetch { [weak self] _ in
|
|
if let free = service.free,
|
|
let paid = service.paid {
|
|
self?.update(free: free, paid: paid)
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|