You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

487 lines
20 KiB

//
// ExchangeRateViewController.swift
// GMERemittance
//
// Created by gme_2 on 20/08/2018.
// Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
//
import UIKit
import Hex
enum PaymentMode: String {
case cashDelivery = "1"
case bankDeposite = "2"
case homeDelivery = "12"
case mobileWallet = "13"
}
class ExchangeRateViewControllerV2: UIViewController {
struct Constants {
static let transferFeeDetailText = "Transfer Fee Included"
static let currentExchangeRateText = "Current Exchange Rate"
static let paymentModeHeightConstant: CGFloat = 193
}
struct ApiConstants {
static let recieverCountryId = "pCountry"
static let senderCurrency = "sCurrency"
static let recieverCurrency = "pCurrency"
static let senderAmount = "cAmount"
static let recieverAmount = "pAmount"
static let paymentMethod = "serviceType"
static let calcBy = "calcBy"
static let senderCountryName = "pCountryName"
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var exchangeBackground1: UIView!
@IBOutlet weak var exchangeBackground2: UIView!
@IBOutlet weak var dropDownImageView: UIImageView!
@IBOutlet weak var backgroundViewCountryLabel1: UIView!
@IBOutlet weak var backgroundViewCountryLabel2: UIView!
@IBOutlet weak var countryListStackView: UIStackView!
@IBOutlet weak var countryCodeLabel: UILabel!
@IBOutlet weak var countryFlagImage: UIImageView!
@IBOutlet weak var paymentModeStackViewConstraint: NSLayoutConstraint!
@IBOutlet weak var paymentModeStackView: UIStackView!
@IBOutlet weak var senderTextField: UITextField!
@IBOutlet weak var reciepientTextField: UITextField!
@IBOutlet weak var transferFeeInfoLabel: UILabel!
@IBOutlet weak var exchangeRateInfoLabel: UILabel!
var countryListTapGuesture: UITapGestureRecognizer?
var selectedPaymentIndex: IndexPath = IndexPath.init(row: 0, section: 0)
var nativeCountry: String? = "Nepal"
var calcBy = ""
var exchangeRateModels: [ExchangeRateModel]? {
didSet {
// added default label if there is native country
if let defaultExchangeRate = self.exchangeRateModels?.filter({
($0.country ?? "").lowercased() == (self.nativeCountry ?? "").lowercased()
}).first {
// there is native country, defaultExchangeRate is the information for that country
self.setCountryFlag(countryCode: defaultExchangeRate.countryCode ?? "")
self.setCurrencyLabel(currency: defaultExchangeRate.currency ?? "")
// set the default amount for this country. there are some default values in CountryInfo
self.populateDefaultAmounts()
self.selectedExchageRateModel = defaultExchangeRate
self.collectionView.reloadData()
showPaymentModeView()
}
}
}
var selectedExchageRateModel: ExchangeRateModel? {
didSet {
self.setCurrencyLabel(currency: self.selectedExchageRateModel?.currency ?? "")
self.setCountryFlag(countryCode: self.selectedExchageRateModel?.countryCode ?? "")
collectionView.reloadData()
}
}
// Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
setupDelegates()
setupTargets()
setupNavigation()
setupDefaultCountryFlagandCurrency()
// todo: show default native country and falg
// Do any additional setup after loading the view.
// populateDefaultAmounts()
fetchExchangeRateInformation()
}
func setupDefaultCountryFlagandCurrency() {
if let defaultExchangeRate = self.exchangeRateModels?.filter({
($0.country ?? "").lowercased() == (self.nativeCountry ?? "").lowercased()
}).first {
// there is native country, defaultExchangeRate is the information for that country
self.setCountryFlag(countryCode: defaultExchangeRate.countryCode ?? "")
self.setCurrencyLabel(currency: defaultExchangeRate.currency ?? "")
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.title = "Today's Rate"
}
// IBActions
@IBAction func calculateExchangeRate(_ sender: UIButton) {
let senderAmount = self.senderTextField.text!
let reciepientAmount = self.reciepientTextField.text!
print("sender textfield \(senderAmount)")
print("reciepientTextfield \(reciepientAmount)")
print(calcBy)
let recipientCurrency = self.selectedExchageRateModel?.currency
let reciepientCountryId = self.selectedExchageRateModel?.countryId
let paymentMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: selectedPaymentIndex.row)
self.calculate(senderAmt: senderAmount, recieverAmt: reciepientAmount, recieverCurrency: recipientCurrency, recieverCountryId: reciepientCountryId, paymentMethod: paymentMethod?.id, calcBy: self.calcBy)
// call calculate( ... ) function
// todo send to api for calculation
}
func calculate(senderAmt: String?, senderCurrency: String? = "KWR", recieverAmt: String?, recieverCurrency: String?, recieverCountryId: String?, paymentMethod: String?, calcBy: String?, senderCountryName: String? = "KOREA", shouldShowLoading: Bool = true ) {
let param: [String: String] =
[
ApiConstants.senderAmount : senderAmt ?? "",
ApiConstants.senderCurrency : senderCurrency ?? "",
ApiConstants.recieverAmount : recieverAmt ?? "",
ApiConstants.recieverCurrency : recieverCurrency ?? "",
ApiConstants.recieverCountryId : recieverCountryId ?? "",
ApiConstants.paymentMethod: paymentMethod ?? "",
ApiConstants.calcBy : calcBy ?? "",
ApiConstants.senderCountryName : senderCountryName ?? ""
]
print(param)
// todo
if shouldShowLoading { self.showProgressHud() }
self.getExchangeRateInformation(params: param, success: { (exchageRateDetail) in
self.senderTextField.text = exchageRateDetail?.senderAmount
self.reciepientTextField.text = exchageRateDetail?.recipientAmount
let transferFee = exchageRateDetail?.transferFee ?? ""
let currency = exchageRateDetail?.senderCurrency ?? ""
self.transferFeeInfoLabel.text = "\(transferFee) \(currency) (\(Constants.transferFeeDetailText))"
let exchangeRate = exchageRateDetail?.exchangeRate ?? ""
self.exchangeRateInfoLabel.text = "\(exchangeRate) (\(Constants.currentExchangeRateText))"
self.hideProgressHud()
}) { (error) in
self.hideProgressHud()
self.alert(message: error.localizedDescription)
}
// call api with these params
}
@objc func showCountryList(_ sender: UITapGestureRecognizer) {
print("show Country List")
let viewcontroller = UIStoryboard.init(name: "TableViewPicker", bundle: nil).instantiateViewController(withIdentifier: "TablePickerViewController") as! TablePickerViewController
viewcontroller.data = self.exchangeRateModels ?? []
viewcontroller.type = TablePickerViewTitle.country
viewcontroller.doneAction = self.countrySelected
// viewcontroller.defaultSelectedData = [self.selectedExchageRateModel]
self.present(viewcontroller, animated: true, completion: nil)
}
// other function
func showPaymentModeView() {
UIView.animate(withDuration: 0.33) {
self.paymentModeStackViewConstraint.constant = Constants.paymentModeHeightConstant
self.paymentModeStackView.alpha = 1
self.view.layoutIfNeeded()
}
}
func countrySelected(model: [ExchangeRateModel]) {
self.selectedExchageRateModel = model.first
// show country with flag.
}
@objc private func textChanged(sender: UITextField) {
switch sender {
case senderTextField:
self.reciepientTextField.text = ""
self.calcBy = "c"
case reciepientTextField:
self.senderTextField.text = ""
self.calcBy = "p"
default:
break
}
}
private func setCountryFlag(countryCode: String) {
let flag = CountryInfo().getFlag(for: countryCode)
self.countryFlagImage.image = flag
}
private func setCurrencyLabel(currency: String) {
self.countryCodeLabel.text = currency.uppercased()
}
private func populateDefaultAmounts() {
guard let nativeCountry = self.nativeCountry else {return}
// todo: native country cha bhane tesko CountryInfo class ma defaullt value cha ki chaina herne
// CountryInfo class ma defaullt value cha bhane tyo value rakhera second api hit garna paryo ani aako data dekhaune
// natra bhane tesko 1000000 kwr ko native ma kati huncha teti populate garaune
guard let exchangeModel = self.exchangeRateModels?.filter({
$0.country?.lowercased() == nativeCountry.lowercased()
}).first else {return}
// self.selectedExchageRateModel = exchangeModel
// if there is no default amount, then we have to calculate from korean won. so guard ma rakhna thik nahola, yo case hereko chaina
if let recievingAmount = CountryInfo().getDefaultSendingAmount(for: exchangeModel.countryCode ?? "") {
self.setDefaultValuesForCountriesHavingDefaultValue(recievingAmount: recievingAmount, exchangeModel: exchangeModel)
} else {
setDefaultValuesForCountriesNotHavingDefaultValue()
}
}
private func setDefaultValuesForCountriesNotHavingDefaultValue() {
let senderAmount = CountryInfo().getDefaultSendingMoneyInKoreanWon()
self.senderTextField.text = senderAmount
let senderCurrency = "KWR"
let recieverCurrency = self.selectedExchageRateModel?.currency
let recieverCountryId = self.selectedExchageRateModel?.countryId
let paymentMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: selectedPaymentIndex.row)
let calcBy = "c"
let senderCountryName = "KOREA"
self.calculate(senderAmt: senderAmount, senderCurrency: senderCurrency, recieverAmt: nil, recieverCurrency: recieverCurrency, recieverCountryId: recieverCountryId, paymentMethod: paymentMethod?.id, calcBy: calcBy, senderCountryName: senderCountryName, shouldShowLoading: false)
}
private func setDefaultValuesForCountriesHavingDefaultValue(recievingAmount: String, exchangeModel: ExchangeRateModel) {
guard let recievingCurrency = CountryInfo().getDefaultSendingCurrency(for: exchangeModel.countryCode ?? ""),
let recievingCountryId = exchangeModel.countryId,
let paymentMethod = exchangeModel.availableServices?.elementAt(index: selectedPaymentIndex.row)
else {
// do something if you have to do
return
}
self.calcBy = "p"
self.reciepientTextField.text = recievingAmount
self.calculate(senderAmt: nil, senderCurrency: "KRW", recieverAmt: recievingAmount, recieverCurrency: recievingCurrency, recieverCountryId: recievingCountryId, paymentMethod: paymentMethod.id, calcBy: calcBy, senderCountryName: self.selectedExchageRateModel?.country, shouldShowLoading: false)
}
private func fetchExchangeRateInformation() {
self.showProgressHud()
self.fetchCountryCurrencyInfo(success: { (models) in
self.exchangeRateModels = models
}) { (error) in
self.hideProgressHud()
self.alert(message: error.localizedDescription)
}
}
private func setupTargets() {
let tapGuesture = UITapGestureRecognizer(target: self, action: #selector(self.showCountryList(_:)))
self.countryListTapGuesture = tapGuesture
self.countryListStackView.addGestureRecognizer(self.countryListTapGuesture!)
self.reciepientTextField.addTarget(self, action: #selector(self.textChanged(sender:)), for: UIControlEvents.editingChanged)
self.senderTextField.addTarget(self, action: #selector(self.textChanged(sender:)), for: UIControlEvents.editingChanged)
}
private func setupDelegates() {
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
private func setup() {
let dropDownImage = #imageLiteral(resourceName: "dropdown_white").withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let image = dropDownImage
self.dropDownImageView.image = image
self.dropDownImageView.tintColor = UIColor.white
self.paymentModeStackViewConstraint.constant = 0
self.paymentModeStackView.alpha = 0
// corner Radius
[backgroundViewCountryLabel1, backgroundViewCountryLabel2].forEach({
$0?.layer.cornerRadius = 5
})
[exchangeBackground1, exchangeBackground2].forEach({
$0?.layer.borderWidth = 1
$0?.layer.borderColor = UIColor.init(hex: "#E0E0E0").cgColor
$0?.layer.cornerRadius = 5
})
}
private func setupNavigation() {
var backBtnImage = #imageLiteral(resourceName: "backIconBlack")
backBtnImage = backBtnImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
self.navigationController!.navigationBar.backIndicatorImage = backBtnImage
self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = backBtnImage
self.navigationController?.navigationBar.barTintColor = UIColor.white
}
}
extension ExchangeRateViewControllerV2: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ExchangeRateCollectionViewCell
self.selectedPaymentIndex = indexPath
self.collectionView.reloadData()
}
}
extension ExchangeRateViewControllerV2: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.selectedExchageRateModel?.availableServices?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let service = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
guard let index = PaymentMode.init(rawValue: service?.id ?? "") else {
return UICollectionViewCell()
}
switch index {
case .bankDeposite:
return configureBankDepositeCell(collectionView: collectionView, indexPath: indexPath)
case .cashDelivery:
return configureCashDeliveryCell(collectionView: collectionView, indexPath: indexPath)
case .homeDelivery:
return configureHomeDeliveryCell(collectionView: collectionView, indexPath: indexPath)
case .mobileWallet:
return configureWalletDeliveryCell(collectionView: collectionView, indexPath: indexPath)
}
}
func configureBankDepositeCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
cell.cellSelected = self.selectedPaymentIndex == indexPath
cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
cell.image = #imageLiteral(resourceName: "ic_bank")
cell.setup()
return cell
}
func configureWalletDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
cell.cellSelected = self.selectedPaymentIndex == indexPath
cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
cell.image = #imageLiteral(resourceName: "wallet-transfer")
cell.setup()
return cell
}
func configureCashDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
cell.cellSelected = self.selectedPaymentIndex == indexPath
cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
cell.image = #imageLiteral(resourceName: "ic_cash")
cell.setup()
return cell
}
func configureHomeDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
cell.cellSelected = self.selectedPaymentIndex == indexPath
cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
cell.image = #imageLiteral(resourceName: "ic_homeDelivery")
cell.setup()
return cell
}
}
extension ExchangeRateViewControllerV2: FetchCountryCurrencyInformation, getExchangeRateInformation {}
extension ExchangeRateViewControllerV2 {
func createTestModel() {
let service1 = PaymentServiceType()
service1.id = "1"
service1.type = "cash"
service1.subtitle = "1 business day"
let service2 = PaymentServiceType()
service2.id = "2"
service2.type = "bank"
service2.subtitle = "2 hour"
let service3 = PaymentServiceType()
service3.id = "3"
service3.type = "home"
service3.subtitle = "5 business day"
let model = ExchangeRateModel()
model.country = "Nepal"
model.countryCode = "Np"
model.countryId = "1"
model.currency = "NRS"
model.availableServices = [service2, service1]
let model1 = ExchangeRateModel()
model1.country = "Korea"
model1.countryCode = "krw"
model1.countryId = "2"
model1.currency = "KRW"
model1.availableServices = [service2, service1, service3]
let model2 = ExchangeRateModel()
model2.country = "India"
model2.countryCode = "in"
model2.currency = "INR"
model2.countryId = "3"
model2.availableServices = [service2]
let model3 = ExchangeRateModel()
model3.country = "China"
model3.countryCode = "cn"
model3.currency = "CN"
model3.countryId = "4"
model3.availableServices = [service2, service1, service3]
let model4 = ExchangeRateModel()
model4.country = "Cambodia"
model4.countryCode = "Kh"
model4.currency = "USD"
model4.countryId = "5"
model4.availableServices = [service2, service1, service3]
let model5 = ExchangeRateModel()
model5.country = "Vietnam"
model5.countryCode = "Vn"
model5.currency = "VND"
model5.countryId = "6"
model5.availableServices = [service2, service1, service3]
}
}