// // HomeViewController.swift // GMERemittance // // Created by gme_2 on 21/09/2018. //Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved. // import UIKit import Crashlytics import Localize_Swift class HomeViewController: UIViewController, UICollectionViewDelegateFlowLayout { enum Sections: Int { case balance = 0 case collection } struct Constants { static let verificationNoticeHeight: CGFloat = 100 } struct StringConstants { let homeText = "home_text".localized() let registerProcessText = "complete_your_registration_text".localized() let registrationApprovalText = "verification_in_aproval_process_text".localized() let pennyTestPrimaryBankText = "complete_penny_test".localized() let verifyTitleText = "kyc_fill_text".localized() let continueRegistrationTitleText = "penny_test_pending_text".localized() let verificationInProcessTitleText = "kyc_verify_pending_text".localized() let soonToUseGmeServicesTitle = "verification_in_aproval_process_text".localized() } // MARK: IBOutlets @IBOutlet weak var tableView: UITableView! @IBOutlet weak var verificationNoticeHeightConstraint: NSLayoutConstraint! @IBOutlet var verificationNoticeView: UIView! @IBOutlet weak var verificationCloseButton: UIButton! @IBOutlet weak var verificationText: UILabel! @IBOutlet var tapGuesture: UITapGestureRecognizer! @IBOutlet weak var verificationTitleLabel: UILabel! @IBOutlet weak var verificationHeaderLeftImageview: UIImageView! @IBOutlet weak var verificationHeaderRightButton: UIButton! @IBOutlet weak var seperatorView: UIView! // title labels @IBOutlet weak var thankyouTitleLabel: UILabel! // MARK: Properties var refreshControl: UIRefreshControl? var presenter: HomeModuleInterface? var user: User? { didSet { // update self.save(user: user) self.showUnverifiedNotice() self.tableView.reloadData() updateBalance() self.update() } } var sections: [Sections] = [.balance, .collection] var menuHeight: CGFloat? { didSet { self.tableView.reloadData() } } // MARK: VC's Life cycle override func viewDidLoad() { super.viewDidLoad() // test() setupNavigationNotifications() self.setup() } func test() { let web = WkWebViewController() web.url = "http://gmeuat.gmeremit.com:5013/kftcCallback?code=b894944b-c500-4627-9cf9-9fc5fd3f2822&scope=login+inquiry+transfer&client_info=f6Qv6Xd44Q5hmkcYLNVH8w%3D%3D" // web.url = "http://gmeuat.gmeremit.com:5013/test.html" // self.present(web, animated: true, completion: nil) self.navigationController?.pushViewController(web, animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureViews() self.setActionBarIcons(showNotificationParameter: false) // set true if there is unread self.tableView.reloadData() NotificationCenter.default.addObserver(self, selector: #selector(updateTabBarTitle), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" } // MARK: IBActions @IBAction func closeVerificationNotice(_ sender: UIButton) { return if #available(iOS 10.0, *) { let animator = UIViewPropertyAnimator(duration: 0.4, curve: .easeOut ) animator.addAnimations { self.verificationNoticeView.alpha = 0 } animator.addAnimations({ self.verificationNoticeHeightConstraint.constant = 0 self.view.layoutIfNeeded() }, delayFactor: 0.5) animator.startAnimation() } } // MARK: Other Functions private func setup() { // all setup should be done here setupDelegates() setupNotifications() configureLanguage() self.addRefreshControlTableView() self.presenter?.refreshData() NotificationCenter.default.addObserver(self, selector: #selector(self.showPennyTestFirstTime), name: NSNotification.Name.init("showPennyTestFirstTime"), object: nil) } @objc private func configureLanguage() { // self.barButtonItem.title = StringConstants().homeText } @objc private func showPennyTestFirstTime() { presenter?.showPennyTest() } private func update() { let platform = self.user?.platforms ?? [] guard let ios = platform.filter({ $0.os ?? "" == "IOS" }).first else {return} let critical = ios.critical ?? "N" UserDefaults.standard.set(critical, forKey: AppConstants.criticalUpdate) let version = Utility.getAppVersion() ?? "" let val = version.components(separatedBy: ".") let latestVersion = ios.version ?? "0" let latestVal = latestVersion.components(separatedBy: ".").last ?? "0" if val.count == 3 { if let build = val.last { if (Int(latestVal) ?? 0) > (Int(build) ?? 0) { self.presenter?.showAppUpdate() } } } } private func updateBalance() { let balance = user?.availableBalance ?? "" UserDefaults.standard.set(balance, forKey: UserKeys.availableBalance) let userInfo = [SideMenuNavigationNotifications.availableBalance : balance] NotificationCenter.default.post(name: self.getAvailableBalanceNotificationName(), object: nil, userInfo: userInfo) self.tableView.reloadData() } private func setupNavigationNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(self.showAutoDebit), name: self.getKftcAccountListNotificationName(), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.showWithdraw), name: self.getWithdrawNotificationName(), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.showSideMenuAboutGme), name: self.getAboutMeNotificationName(), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.showSideMenuSupport), name: self.getSupportNotificationName(), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.showSideMenuSetting), name: self.getSettingNotificationName(), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.showTransactionStatement), name: self.getTransactionHistoryNotificationName(), object: nil) } private func getAboutMeNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.aboutGme) } private func getTransactionHistoryNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.transactionHistory) } private func getSupportNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.support) } private func getSettingNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.setting) } @objc private func showSideMenuAboutGme() { let vc = UIStoryboard.init(name: "_Home", bundle: nil).instantiateViewController(withIdentifier: "AboutGMEViewController") as! AboutGMEViewController self.navigationController?.pushViewController(vc, animated: true) } @objc private func showSideMenuSetting() { let vc = UIStoryboard.init(name: "Setting", bundle: nil).instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController self.navigationController?.pushViewController(vc, animated: true) } @objc private func showSideMenuSupport() { let vc = UIStoryboard.init(name: "_Home", bundle: nil).instantiateViewController(withIdentifier: "SupportViewController") as! SupportViewController self.navigationController?.pushViewController(vc, animated: true) } @objc private func showAutoDebit() { let wireframe = AutoDebitWireframe() if let navigation = self.navigationController { wireframe.pushMainView(in: navigation) } } @objc private func showWithdraw() { let vc = UIStoryboard.init(name: "autoRefund", bundle: nil).instantiateViewController(withIdentifier: "AutoRefundsViewController") as! AutoRefundsViewController self.navigationController?.pushViewController(vc, animated: true) } private func setupDelegates() { tableView.delegate = self tableView.dataSource = self self.tapGuesture.delegate = self } private func addRefreshControlTableView() { let colorOption = [NSAttributedStringKey.foregroundColor : AppConstants.themWhiteColor]; let title = NSAttributedString(string: "pull to refresh", attributes: colorOption) let refreshControl = UIRefreshControl() refreshControl.attributedTitle = title refreshControl.backgroundColor = AppConstants.themeBlueColor refreshControl.tintColor = AppConstants.themWhiteColor refreshControl.addTarget(self, action: #selector(self.refresh), for: .valueChanged) self.refreshControl = refreshControl if #available(iOS 10.0, *) { tableView.refreshControl = self.refreshControl } else { if let control = self.refreshControl { tableView.addSubview(control) } } } @objc private func refresh() { presenter?.refreshData() } @objc func showNotification(){ performSegue(withIdentifier: "notification", sender: nil) } @objc func showSupport() { let alert = UIAlertController(title:nil, message:"help_you_text".localized(), preferredStyle: .actionSheet) // alert.view.subviews.last?.subviews.last?.backgroundColor = UIColor.darkGray let liveChat = UIAlertAction(title: "Live Chat", style: .default) { UIAlertAction in } let contactNumber = UIAlertAction(title: "1588 6864", style: .default) { UIAlertAction in self.startCall(contactNumber: "1588 6864") } let supportEmail = UIAlertAction(title: "support@gmeremit.com", style: .default) { UIAlertAction in let storyboard = UIStoryboard.init(name: "MessageCompose", bundle: Bundle.main) if let messageViewController = storyboard.instantiateViewController(withIdentifier: "message") as? MessageComposeViewController { self.navigationController!.pushViewController(messageViewController, animated: true) } } liveChat.setValue(UIImage(named:"ic_live_chat")?.withRenderingMode(.alwaysOriginal),forKey:"image") contactNumber.setValue(UIImage(named:"ic_call")?.withRenderingMode(.alwaysOriginal),forKey:"image") supportEmail.setValue(UIImage(named:"ic_email")?.withRenderingMode(.alwaysOriginal),forKey:"image") // TODO: have to enable when zendesk is provided // alert.addAction(liveChat) alert.addAction(contactNumber) // alert.addAction(supportEmail) alert.view.tintColor = UIColor.darkGray // alert.view.subviews.last?.subviews.last?.layer.cornerRadius = 10 alert.addAction(UIAlertAction(title: "cancel_text".localized(), style: UIAlertActionStyle.cancel, handler: nil)) present(alert, animated: true, completion: nil) } func startCall(contactNumber: String){ if let url = URL(string: "tel://\(contactNumber.removeWhitespacesInBetween())"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } } private func setupNotifications() { let center = NotificationCenter.default center.addObserver(self, selector: #selector(self.showSendMoney), name: self.getSendMoneyNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.showMobileRecharge), name: self.getMobileRechargeNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.showTodaysRate), name: self.getTodaysRateNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.showResendMoney), name: self.getTrackYourTransferNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.showTrackYourTransfer), name: self.getTransactionStatementNotificationName(), object: nil) // center.addObserver(self, selector: #selector(self.showResendMoney), name: self.getWalletToWalletNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.setupHeight(sender:)), name: self.getCollectionHeightNotificationName(), object: nil) center.addObserver(self, selector: #selector(self.showUnVerifiedMessage), name: self.getMainControllerNotificationName(), object: nil) } func setActionBarIcons(showNotificationParameter: Bool){ let supportImage = UIImage(named: "ic_support")?.withRenderingMode(.alwaysOriginal) let supportButton = UIBarButtonItem(image:supportImage, style: .plain, target: self, action: #selector(showSupport)) let notificationImage: UIImage! if showNotificationParameter { notificationImage = UIImage(named: "ic_notificationDot")?.withRenderingMode(.alwaysOriginal) } else { notificationImage = UIImage(named: "ic_notification")?.withRenderingMode(.alwaysOriginal) } let notificationButton = UIBarButtonItem(image: notificationImage, style: .plain, target: self, action: #selector(showNotification)) // self.navigationItem.rightBarButtonItems=[notificationButton,supportButton] self.navigationItem.rightBarButtonItems = [supportButton] } private func showUnverifiedNotice() { setVerificationText() if shouldShowUnverifiedNotice() { UIView.animate(withDuration: 0.33) { self.verificationNoticeHeightConstraint.constant = Constants.verificationNoticeHeight self.verificationNoticeView.alpha = 1 self.view.layoutIfNeeded() } }else { self.verificationNoticeHeightConstraint.constant = 0 self.verificationNoticeView.alpha = 0 self.view.layoutIfNeeded() } } private func setVerificationText() { // && Utility.didPennyTestNotInitiated() if didNotSubmitKycAndNotVerified() { verificationTitleLabel.text = StringConstants().verifyTitleText self.verificationText.text = StringConstants().registerProcessText self.verificationHeaderLeftImageview.image = UIImage.init(named: "ic_home_verified") let image = UIImage.init(named: "ic_home_payoutLocation") self.verificationHeaderRightButton.setImage(image, for: UIControlState.normal) }else if didSubmitKycAndNotVerified() && shouldShowPennyTestError() { verificationTitleLabel.text = StringConstants().continueRegistrationTitleText self.verificationText.text = StringConstants().pennyTestPrimaryBankText self.verificationHeaderLeftImageview.image = #imageLiteral(resourceName: "shield.png") self.verificationNoticeHeightConstraint.constant = Constants.verificationNoticeHeight self.verificationNoticeView.alpha = 1 self.verificationHeaderRightButton.isHidden = true } else if didSubmitKycAndNotVerified() { verificationTitleLabel.text = StringConstants().verificationInProcessTitleText self.verificationText.text = StringConstants().soonToUseGmeServicesTitle self.verificationHeaderLeftImageview.image = #imageLiteral(resourceName: "ic_home_verified") self.verificationHeaderRightButton.setImage(#imageLiteral(resourceName: "ic_home_payoutLocation"), for: UIControlState.normal) } if didSubmitKycAndVerified() && !Utility.pennyTestVerified() { verificationTitleLabel.text = StringConstants().continueRegistrationTitleText self.verificationText.text = StringConstants().pennyTestPrimaryBankText self.verificationHeaderLeftImageview.image = #imageLiteral(resourceName: "shield.png") self.verificationNoticeHeightConstraint.constant = Constants.verificationNoticeHeight self.verificationNoticeView.alpha = 1 self.verificationHeaderRightButton.isHidden = true } if didSubmitKycAndVerified() && Utility.pennyTestVerified() { self.verificationNoticeHeightConstraint.constant = 0 self.verificationNoticeView.alpha = 0 } } private func didSubmitKycAndNotVerified() -> Bool { return Utility.didSubmitKyc() && !Utility.isVerifiedUser() } private func didSubmitKycAndVerified() -> Bool { return Utility.didSubmitKyc() && Utility.isVerifiedUser() } private func didNotSubmitKycAndNotVerified() -> Bool { return !Utility.didSubmitKyc() && !Utility.isVerifiedUser() } private func shouldShowPennyTestError() -> Bool { return Utility.shouldShowPennyTestError() } @IBAction func showKyc(_ sender: UITapGestureRecognizer) { if self.didNotSubmitKycAndNotVerified() { self.presenter?.showKyc() }else if shouldShowPennyTestError() { if Utility.didPennyTestRequested() { presenter?.showPennyTestSubmit() }else { presenter?.showPennyTest() } } } private func shouldShowUnverifiedNotice() -> Bool { return !self.isUserVerified() || Utility.shouldShowPennyTestError() } private func configureViews() { self.verificationNoticeHeightConstraint.constant = 0 showUnverifiedNotice() setNavBar() } func setNavBar() { let selector = #selector(self.showSideMenu) self.setupPicturedNavBar(sideMenuAction: selector) } @objc func showSideMenu() { sideMenuController?.showLeftViewAnimated() } private func isUserVerified() -> Bool { return Utility.isVerifiedUser() } @objc private func showSendMoney() { let kycSubmited = user?.kyc ?? false let pennyTestComplete = Utility.pennyTestVerified() if kycSubmited == true && pennyTestComplete == false { self.show(error: StringConstants().pennyTestPrimaryBankText) return } if isUserVerified() { // remaining of previous developer. I dont have much time. Later. TODO: refracor let viewcontroller = UIStoryboard.init(name: "RecipientListViewController", bundle: nil).instantiateViewController(withIdentifier: "RecipientListViewController") as! RecipientListViewController self.navigationController?.pushViewController(viewcontroller, animated: true) } else { self.showUnVerifiedMessage() } } @objc private func showResendMoney() { let kycSubmited = user?.kyc ?? false let pennyTestComplete = Utility.pennyTestVerified() if kycSubmited == true && pennyTestComplete == false { self.show(error: StringConstants().pennyTestPrimaryBankText) return } if isUserVerified() { // remaining of previous developer. I dont have much time. Later. TODO: refracor if let navigation = self.navigationController { let wireframe = ResendWireframe() wireframe.pushMainView(in: navigation) } } else { self.showUnVerifiedMessage() } } @objc private func showMobileRecharge() { let kycSubmited = user?.kyc ?? false let pennyTestComplete = Utility.pennyTestVerified() if kycSubmited == true && pennyTestComplete == false { self.show(error: StringConstants().pennyTestPrimaryBankText) return } self.alert(message: "This feature is coming soon") return if isUserVerified() { return self.performSegue(withIdentifier: "mobileRecharge", sender: nil) }else { self.showUnVerifiedMessage() } } @objc private func showTodaysRate() { presenter?.openTodaysRate() } // Transaction Report @objc private func showTrackYourTransfer() { let kycSubmited = user?.kyc ?? false let pennyTestComplete = Utility.pennyTestVerified() if kycSubmited == true && pennyTestComplete == false { self.show(error: StringConstants().pennyTestPrimaryBankText) return } isUserVerified() ? (presenter?.openTrackYourTransfer()) : (self.showUnVerifiedMessage()) } @objc private func showTransactionStatement() { let kycSubmited = user?.kyc ?? false let pennyTestComplete = Utility.pennyTestVerified() if kycSubmited == true && pennyTestComplete == false { self.show(error: StringConstants().pennyTestPrimaryBankText) return } isUserVerified() ? (presenter?.openTransactionHistory()) : (self.showUnVerifiedMessage()) } @objc private func showUnVerifiedMessage() { if didNotSubmitKycAndNotVerified() { self.alert(message: StringConstants().registerProcessText) } else if Utility.didSubmitKyc() && !Utility.pennyTestVerified() { self.alert(message: StringConstants().pennyTestPrimaryBankText) } else if didSubmitKycAndNotVerified() { // verification_in_aproval_process_text // Your registration request is in approval process. You will soon be able to use GME services. self.alert(message: "verification_in_aproval_process_text".localized()) } } // TODO:- @objc private func showUnVerifiedPennyTestMessage() { // complete_penny_test self.alert(message: "complete_penny_test".localized()) } @objc private func showWalletToWallet() { self.alert(message: "This feature is coming soon") } @objc private func setupHeight(sender: Notification) { if let height = sender.userInfo?[MenuNotificationName.collectionHeight] as? CGFloat { self.menuHeight = height } } } // MARK: HomeViewInterface extension HomeViewController: HomeViewInterface { func show(model: User) { self.user = model } func show(error: String) { self.alert(message: error) } func show(panicError: String) { self.alert(message: panicError, title: "Warning") { self.presenter?.logout() } } func showLoading() { self.showProgressHud() } func hideLoading() { self.hideProgressHud() } func endRefreshing() { if #available(iOS 10.0, *) { guard let control = self.tableView.refreshControl else {return} if control.isRefreshing == true { DispatchQueue.main.async { control.perform(#selector(control.endRefreshing), with: nil, afterDelay: 0.5) } } } else { // Fallback on earlier versions } } } extension HomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let _section = Sections.init(rawValue: indexPath.section) else {return 0} switch _section { case .balance: return UITableViewAutomaticDimension case .collection: let totalHeight = view.frame.height let ramainingBalanceCellHeight: CGFloat = 100 let finalHeight = totalHeight - ramainingBalanceCellHeight return finalHeight } } } extension HomeViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let _section = Sections.init(rawValue: indexPath.section) else {return UITableViewCell()} switch _section { case .balance: return configureRemainingLimitCell(tableView: tableView, indexPath: indexPath) case .collection: return configureCollectionCell(tableView: tableView, indexPath: indexPath) } } func configureRemainingLimitCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HomeRemainingLimitTableViewCell") as! HomeRemainingLimitTableViewCell cell.user = self.user cell.setup() return cell } func configureCollectionCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCollectionTableViewCell") as! HomeCollectionTableViewCell cell.setup() return cell } override func setupTabItem() { let image = UIImage.init(named: "ic-home") self.tabBarItem = UITabBarItem(title: "home_text".localized(), image: image, selectedImage: nil) self.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: UI_USER_INTERFACE_IDIOM() == .pad ? 2 : -6) } @objc func updateTabBarTitle() { self.tabBarItem.title = "home_text".localized() } } // notification Name extension HomeViewController { func getSendMoneyNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.sendMoney) } func getMobileRechargeNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.mobileRecharge) } func getTodaysRateNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.todaysRate) } func getTrackYourTransferNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.resend) } func getTransactionStatementNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.transactionStatement) } func getWalletToWalletNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.walletToWallet) } func getCollectionHeightNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: MenuNotificationName.collectionHeight) } func getAvailableBalanceNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: SideMenuNavigationNotifications.availableBalance) } func getMainControllerNotificationName() -> Notification.Name { return Notification.Name.init(rawValue: AppConstants.MainWireFrameNotificationName) } func getWithdrawNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.withdraw) } func getKftcAccountListNotificationName() -> Notification.Name { return Notification.Name.init(SideMenuNavigationNotifications.KftcAccountList) } } extension HomeViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return !Utility.didSubmitKyc() || Utility.shouldShowPennyTestError() || Utility.didPennyTestCancelled() || Utility.didPennyTestRequested() || Utility.didPennyTestNotInitiated() } } extension HomeViewController { private func save(value: Any?, forKey: String) { let defaults = UserDefaults.standard defaults.set(value, forKey: forKey) } func save(user: User?) { Utility.save(user: user) } }