Files
raspberry/iOS/Wallet/Sources/CCCP/Controller/CCCPControllerCreateExchangeRequest.swift
2022-05-27 20:21:01 +03:00

177 lines
7.8 KiB
Swift

//
// CCCPControllerCreateExchangeRequest.swift
// PayCash
//
// Created by Saveliy Stavitsky on 7/30/20.
// Copyright © 2020 List. All rights reserved.
//
import UIKit
private typealias Contract = Network.Model.Contract
private typealias BlockchainAction = Network.Model.Blockchain.Action
class CCCPControllerCreateExchangeRequest: UIViewController {
@IBOutlet private var mainStackView: UIStackView!
@IBOutlet private weak var tokeGiveView: CommonViewCard!
@IBOutlet private var labelsStackView: UIStackView!
@IBOutlet private weak var youSendInfoLbl: CommonViewInfoLabel!
@IBOutlet private weak var youGiveInfoLbl: CommonViewInfoLabel!
@IBOutlet private weak var youGetInfoLbl: CommonViewInfoLabel!
@IBOutlet var youGiveTokenSelectorView: CCCPViewTokenSelector!
@IBOutlet var warning1Label: UILabel!
@IBOutlet var youGetTokenSelectorView: CCCPViewTokenSelector!
@IBOutlet var warning2Label: UILabel!
@IBOutlet var createRequestButton: CommonButtonAction!
var cashTokens: [Network.Model.Token] { Wallet.Service.Tokens.shared.cashTokens }
var tokens: [Network.Model.Token] { Wallet.Service.Tokens.shared.balances.collection }
var selectedTokens: (Network.Model.Token, Network.Model.Token)? {
guard let tokenGive = youGiveTokenSelectorView.selectedToken,
let cashTokenGive = cashTokens.first(where: { $0.symbol == tokenGive.symbol }) else {
return nil
}
return (tokenGive, cashTokenGive)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = L10n.Cccp.CreateExchangeRequest.title
navigationItem.leftBarButtonItem = .pop(self)
youGiveTokenSelectorView.titleLabel.text = L10n.Cccp.DestroyTokens.youGiveTitle
youGiveTokenSelectorView.secondTitleLabel.isHidden = true
youGiveTokenSelectorView.notesTitleLabel.text = L10n.Cccp.DestroyTokens.youGiveYouGiveTitle
youGiveTokenSelectorView.countSectionStackView.isHidden = true
youGiveTokenSelectorView.balanceStackView.isHidden = false
youGiveTokenSelectorView.parentViewController = self
youGetTokenSelectorView.secondTitleLabel.isHidden = true
youGetTokenSelectorView.countSectionStackView.isHidden = true
youGetTokenSelectorView.currencyPickerSectionStackView.isHidden = true
youGetTokenSelectorView.currencySectionImageView.isHidden = true
youGetTokenSelectorView.notesTitleLabel.text = L10n.Cccp.DestroyTokens.youGetYouGetTitle
youGetTokenSelectorView.parentViewController = self
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4.0
warning1Label.attributedText = L10n.Cccp.OutgoingExchangeRequest.warning1.attributed
.applying(attribute: .paragraphStyle, value: paragraphStyle)
warning2Label.attributedText = L10n.Cccp.OutgoingExchangeRequest.warning2.attributed
.applying(attribute: .paragraphStyle, value: paragraphStyle)
observers.append(contentsOf: [
Notification.subscribe(name: .didChangeAccount) { _ in Loader.show() },
Notification.subscribe(name: .didUpdateBalances) { [weak self] _ in self?.setupView() }
])
setupView()
}
var observers: [AnyObject] = []
deinit { observers.forEach({ Notification.unsubscribe(observer: $0) }) }
func setupView() {
youGiveTokenSelectorView.tokens = tokens
.filter { cashTokens.contains($0) }
tokeGiveView.action = .cards(
tokens: youGiveTokenSelectorView.tokens,
selected: youGiveTokenSelectorView.selectedToken,
empty: .menu(
image: Asset.commonToken.image.tinted(with: Asset.deepWater.color),
title: L10n.Cccp.CreateExchangeRequest.titleCard
)
) { [weak self] in
self?.youGiveTokenSelectorView.index = self?.youGiveTokenSelectorView.tokens.index(of: $0.uuid) ?? -1
}
Loader.hide()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Accounts().isLocked = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Accounts().isLocked = false
}
@IBAction func createRequestPressed(_ sender: Any) {
guard let username = Accounts().current?.username,
let (_, cashTokenGive) = selectedTokens else { return }
let amount = cashTokenGive.certCoef
.toCanonicalString(precision: cashTokenGive.precision, symbol: cashTokenGive.symbol)
let data = ["creator": username, "volume": amount]
let actions: [(Contract, BlockchainAction, Codable)] = [(.cash, .cashCreatereq, data)]
Popup.show(title: navigationItem.title, views: [labelsStackView], submit: L10n.Common.Button.confirm, in: self, { [unowned self] ctrl in
AccountViewAuthorize.showGetPrivateKey(in: self) {
Loader.show(in: ctrl)
Network.Service.Blockchain.execute(actions: actions, privateKeys: [$0]) { result in
Loader.hide(in: ctrl)
ctrl.dismiss(animated: true)
switch result {
case .success(let trxId):
Account.Service.History.shared.current?.fetchUntil(trxId: trxId)
delayed(0.5) { //needed because labelsStackView will free inly after previous popup hde
Popup.show(title: L10n.Cccp.CreateExchangeRequest.createdTitle,
views: [labelsStackView], in: self)
}
case let .failure(error):
Alert.notify(error, pop: self)
}
}
}
}, { [weak self] in
guard let self = self else { return }
self.mainStackView.addArrangedSubview(self.labelsStackView)
})
}
}
extension CCCPControllerCreateExchangeRequest: CCCPViewTokenSelectorDelegate {
func stateChanged() {
//Reset appearance
youGiveTokenSelectorView.notesSectionSubStackView.arrangedSubviews
.forEach({ $0.removeFromSuperview() })
youGetTokenSelectorView.notesSectionSubStackView.arrangedSubviews
.forEach({ $0.removeFromSuperview() })
youGiveInfoLbl.clearErrors()
createRequestButton.isEnabled = false
guard let (tokenGive, cashTokenGive) = selectedTokens else { return }
labelsStackView.isHidden = false
//Cash token select section view appearance
let labelCashTokens = CCCPLabelAddMoneyColored(sign: "-", amount: cashTokenGive.certCoef, symbol: tokenGive.symbol)
youGiveTokenSelectorView.notesSectionSubStackView.addArrangedSubview(labelCashTokens)
let sendCount = "0.9975".toDecimal() * cashTokenGive.certCoef
let cashCount = "0.97".toDecimal() * cashTokenGive.certCoef
let cashSymbol = tokenGive.symbol.uppercased().replacingOccurrences(of: "CASH", with: "")
let labelListTokens = CCCPLabelAddMoneyColored(amount: cashCount, symbol: cashSymbol)
youGetTokenSelectorView.notesSectionSubStackView.addArrangedSubview(labelListTokens)
youSendInfoLbl.updateText("\(cashTokenGive.certCoef.toString(max: 5)) \(tokenGive.symbol)")
youGiveInfoLbl.updateText("\(cashTokenGive.certCoef.toString(max: 5)) \(tokenGive.symbol)")
youGetInfoLbl.updateText("\(cashCount.toString(max: 5)) \(cashSymbol)")
if let amountHave = tokens.first(where: { $0.symbol == cashTokenGive.symbol })?.amount {
if amountHave >= cashTokenGive.certCoef.toString(max: 5, group: false).toDecimal() {
createRequestButton.isEnabled = true
} else {
youGiveInfoLbl.addError(L10n.Cccp.CreateExchangeRequest.youGiveAmountError(cashTokenGive.symbol))
}
}
}
}