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.
 
 
 
 

451 lines
20 KiB

//
// ExchangeRatesViewController.swift
// GMERemittance
//
// Created by gme_2 on 24/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 ExchangeRatesViewController: 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 recieverCountryName = "pCountryName"
static let senderCountryId = "sCountry"
}
// MARK: IBOutlets
@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 presenter: ExchangeRatesModuleInterface?
var countryListTapGuesture: UITapGestureRecognizer?
var selectedPaymentIndex: IndexPath = IndexPath.init(row: 0, section: 0)
var nativeCountryCode: String? = "np"
var calcBy = ""
var exchangeRateModels: [ExchangeRateModel]? {
didSet {
if let _ = CountryInfo().defaultCountryCodes.filter({$0.lowercased() == (self.nativeCountryCode ?? "").lowercased()}).first {
if let defaultExchangeRate = self.exchangeRateModels?.filter({
($0.countryCode ?? "").lowercased() == (self.nativeCountryCode ?? "").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.selectedExchageRateModel = defaultExchangeRate
self.collectionView.reloadData()
showPaymentModeView()
self.populateDefaultAmounts()
}
} else {
self.setDefaultValuesForCountriesNotHavingDefaultValue()
showPaymentModeView()
}
}
}
var selectedExchageRateModel: ExchangeRateModel? {
didSet {
self.setCurrencyLabel(currency: self.selectedExchageRateModel?.currency ?? "")
self.setCountryFlag(countryCode: self.selectedExchageRateModel?.countryCode ?? "")
self.reciepientTextField.text = ""
calcBy = "c"
collectionView.reloadData()
}
}
// MARK: VC's 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.nativeCountryCode ?? "").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)
let reciepientCountryName = self.selectedExchageRateModel?.country
self.calculate(senderAmt: senderAmount, recieverAmt: reciepientAmount, recieverCurrency: recipientCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: reciepientCountryId, paymentMethod: paymentMethod?.id, calcBy: self.calcBy)
// call calculate( ... ) function
// todo send to api for calculation
}
func calculate(senderAmt: String?, senderCurrency: String? = "KRW", recieverAmt: String?, recieverCurrency: String?, recieverCountryName: String?, recieverCountryId: String?, paymentMethod: String?, calcBy: String?, senderCountryId: String? = "118", 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.senderCountryId : senderCountryId ?? "",
ApiConstants.recieverCountryName: recieverCountryName ?? ""
]
print(param)
// todo
if shouldShowLoading { self.showProgressHud() }
self.getExchangeRateInformation(params: param, success: { (exchageRateDetail) in
self.senderTextField.text = Utility.getCommaSeperatedString(numberString: exchageRateDetail?.senderAmount ?? "")
self.reciepientTextField.text = Utility.getCommaSeperatedString(numberString: 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"
senderTextField.text = Utility.getCommaSeperatedString(numberString: senderTextField.text!)
case reciepientTextField:
self.senderTextField.text = ""
self.calcBy = "p"
reciepientTextField.text = Utility.getCommaSeperatedString(numberString: reciepientTextField.text!)
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.nativeCountryCode 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.countryCode?.lowercased() == nativeCountry.lowercased() // countryCode
}).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() {
self.selectedExchageRateModel = self.exchangeRateModels?.first
let senderAmount = CountryInfo().getDefaultSendingMoneyInKoreanWon()
self.senderTextField.text = Utility.getCommaSeperatedString(numberString: senderAmount ?? "")
let senderCurrency = "KWR"
let recieverCurrency = self.selectedExchageRateModel?.currency
let recieverCountryId = self.selectedExchageRateModel?.countryId
let paymentMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: selectedPaymentIndex.row)
let reciepientCountryName = self.selectedExchageRateModel?.country ?? ""
let calcBy = "c"
let senderCountryName = "KOREA"
self.calculate(senderAmt: senderAmount, senderCurrency: senderCurrency, recieverAmt: nil, recieverCurrency: recieverCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: recieverCountryId, paymentMethod: paymentMethod?.id, calcBy: calcBy, 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 = Utility.getCommaSeperatedString(numberString: recievingAmount)
let reciepientCountryName = exchangeModel.country
self.calculate(senderAmt: nil, senderCurrency: "KRW", recieverAmt: recievingAmount, recieverCurrency: recievingCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: recievingCountryId, paymentMethod: paymentMethod.id, calcBy: calcBy, 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
})
}
func show(error: String) {
self.alert(message: error)
}
func showLoading() {
self.showProgressHud()
}
func hideLoading() {
self.hideProgressHud()
}
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 ExchangeRatesViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ExchangeRateCollectionViewCell
self.selectedPaymentIndex = indexPath
self.collectionView.reloadData()
}
}
extension ExchangeRatesViewController: 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 ExchangeRatesViewController: FetchCountryCurrencyInformation, getExchangeRateInformation {}
// MARK: ExchangeRatesViewInterface
extension ExchangeRatesViewController: ExchangeRatesViewInterface {
}