// // AgentBankViewController.swift // GMERemittance // // Created by FMI-12 on 2/2/18. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved. // import UIKit import MapKit class AgentBankViewController: UIViewController { @IBOutlet weak var tableViewAgent: UITableView! var selectedCell:Int? var isSelect:Bool? private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() private var previousIndex: Int = 0 private var selectedIndex: Int = 10000 private var tableRowIndex: Int? /// To get data fron sendmoney agentlocation tap var sendMoneyAgentLocationStatus:Bool = false var selectedCountry: String = "" @IBOutlet weak var searchTextField: UITextField! private var agentCountryList = [AgentCountryList]() private var agentPayoutList = [AgentModel]() var agentCell: AgentTableViewCell? var agentViewModel = AgentViewModel() @IBOutlet weak var bgViewSearchBar: UIView! private var pickerView: UIPickerView = UIPickerView() public static var agentConnectionTimeOutCheck = 0 override func viewWillAppear(_ animated: Bool) { self.tabBarController?.navigationController?.navigationBar.barTintColor = UIColor(hex:0xEC1C24) setUpAnotherLoginListener(genericviewmodel: agentViewModel) } override func viewDidLoad() { super.viewDidLoad() if sendMoneyAgentLocationStatus { setUpNavBar(id: 206, title: "Agent") } else { setUpNavBar(id: 202,title: "") } setTextFieldAndPickerViewDelegate() setTapListenerInBgView() tableViewAgent.tableFooterView = UIView() self.tableViewAgent.delegate = self self.tableViewAgent.dataSource = self self.tableViewAgent.estimatedRowHeight = 119 self.tableViewAgent.rowHeight = UITableViewAutomaticDimension tableViewAgent.sectionIndexColor = UIColor.darkGray tableViewAgent.sectionIndexBackgroundColor = UIColor(hex: 0xe7edf2) agentViewModel.agentConnectionTimeOut.value = nil /** connection timeout */ agentViewModel.agentConnectionTimeOut.bind { [unowned self] in guard $0 != nil else { return } self.stopLoading() if AgentBankViewController.agentConnectionTimeOutCheck == 0{ AgentBankViewController.agentConnectionTimeOutCheck = AgentBankViewController.agentConnectionTimeOutCheck+1 self.popUpMessage(value: 40) } } agentViewModel.internetConnection.value = nil /** Internet check */ agentViewModel.internetConnection.bind { [unowned self] in guard $0 != nil else { return } self.enableUserInteractions() self.dismissActivityIndicator(activityIndicator: self.activityIndicator) self.popUpMessage(value: 15) } /** Update the country list */ agentViewModel.agentCountryListAvailable.bind { [weak self] in guard $0 != nil else { return } self?.stopLoading() guard $0! else { self?.stopLoading() //self.popUpMessageError(value: 10, message: self.agentViewModel.getErrorMessage()); return } self?.stopLoading() self?.setAgentCountryList() } startLoading() self.agentViewModel.fetchListOfCountry() /** Update the agent location */ agentViewModel.agentLocationBool.bind { [unowned self] in guard $0 != nil else { return } self.stopLoading() guard $0! else { self.stopLoading() //self.popUpMessageError(value: 10, message: self.agentViewModel.getErrorMessage()); return } self.stopLoading() self.setAgentLocationList() } } /** Add Tap gesture in Search bar */ func setTapListenerInBgView(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AgentBankViewController.openPickerView)) tap.cancelsTouchesInView = false bgViewSearchBar.addGestureRecognizer(tap) } /** To display Picker view */ @objc func openPickerView(){ if agentCountryList.count > 0{ self.setPickerViewRowAsSelected() self.searchTextField.becomeFirstResponder() } } /** set the country list */ func setAgentCountryList(){ self.agentCountryList = agentViewModel.getCountryList() self.requestPayoutList(requestType: "first") } /** Get Agent location address - return: address list */ func getAgentLocationAddress() -> [String]{ var agentArray = [String]() for agent in agentPayoutList{ if let address = agent.address{ agentArray.append(address) } } return agentArray } /** set the agent location list */ func setAgentLocationList(){ self.agentPayoutList = agentViewModel.getAgentLocation() if self.agentPayoutList.count > 0{ self.tableViewAgent.reloadData() }else{ self.popUpMessageError(value: 10, message: "Payout agent is not available in this location."); } } /** Dispaly loading indicator */ func startLoading(){ self.showActivityIndicator(activityIndicator: self.activityIndicator) self.disableUserInteractions() } /** Hide loading indicator */ func stopLoading(){ self.dismissActivityIndicator(activityIndicator: self.activityIndicator) self.enableUserInteractions() } /** Delegate setup */ func setTextFieldAndPickerViewDelegate(){ searchTextField.delegate = self searchTextField.delegate = self pickerView.dataSource = self pickerView.delegate = self searchTextField.inputView = pickerView } /** Get country list - returns: country list */ func getCountryList() -> [String]{ var countryList = [String]() if agentCountryList.count > 0 { for country in self.agentCountryList{ if let countryName = country.country{ countryList.append(countryName) } } return countryList }else{ } return countryList } /** Display Picker view */ @IBAction func dropDownButtonAction(_ sender: Any) { if getCountryList().count > 0{ self.setPickerViewRowAsSelected() searchTextField.becomeFirstResponder() }else{ } } /** Set selected row of country list in picker view */ func setPickerViewRowAsSelected(){ if let searchText = searchTextField.text{ if let index = self.getCountryList().index(of: searchText){ self.pickerView.selectRow(index, inComponent: 0, animated: true) } } } @IBAction func searchButtonAction(_ sender: Any) { if searchTextField.text != ""{ if self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId != nil{ self.performSegue(withIdentifier: "agentSuccessViewController", sender: nil) } } else{ } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "agentSuccessViewController" { let agentSearchViewController = segue.destination as! AgentSearchViewController agentSearchViewController.countryId = self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId } } //Doing Picker view button func pickUp(_ textField : UITextField){ // UIPickerView self.pickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)) self.pickerView.delegate = self self.pickerView.dataSource = self //self.pickerView.backgroundColor = UIColor.white textField.inputView = self.pickerView // ToolBar let toolBar = UIToolbar() toolBar.barStyle = .default toolBar.isTranslucent = true toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1) toolBar.sizeToFit() // Adding Button ToolBar let customButton = UIButton() customButton.setTitle("Done", for: .normal) customButton.addTarget(self, action: #selector(AgentBankViewController.doneClick), for: .touchUpInside) customButton.setTitleColor(UIColor(hex : 0xED1C24), for: .normal) customButton.frame = CGRect(x: 0, y: 0, width: 60, height: 30) let doneButton = UIBarButtonItem(customView: customButton) let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true textField.inputAccessoryView = toolBar } @objc func doneClick() { self.searchTextField.resignFirstResponder() if self.selectedIndex != 10000{ if self.isSelect == true{ self.isSelect = false searchTextField.leftView = nil self.requestPayoutList(requestType: "later") } } } /** request of country list - parameter requestType: First(Korea) or later(selected country from picker view) */ func requestPayoutList(requestType: String){ startLoading() self.agentPayoutList.removeAll() if requestType == "later"{ searchTextField.text = getCountryList()[self.selectedIndex] if let flagUrl = agentCountryList[selectedIndex].flagUrl{ self.downloadImage(url: Foundation.URL(string: flagUrl)!) } else { } let countryId = self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId agentViewModel.fetchAgentLocation(countryId: countryId!) }else if requestType == "first"{ if !(selectedCountry.isEmpty) { selectedCountryFromSendMoney() } else { if let countryId = self.agentCountryList[getCountryList().index(of: "South Korea")!].countryId,let flagUrl = self.agentCountryList[getCountryList().index(of: "South Korea")!].flagUrl{ searchTextField.text = self.agentCountryList[getCountryList().index(of: "South Korea")!].country self.downloadImage(url: Foundation.URL(string: flagUrl)!) agentViewModel.fetchAgentLocation(countryId: countryId) }else{ } } } } /** To get country Agent List through Sendmoney Page */ func selectedCountryFromSendMoney(){ if let countrySelectedId = self.agentCountryList[getCountryList().index(of: selectedCountry)!].countryId, let countrySeletedflagUrl = self.agentCountryList[getCountryList().index(of: selectedCountry)!].flagUrl { searchTextField.text = self.agentCountryList[getCountryList().index(of: selectedCountry)!].country self.downloadImage(url: Foundation.URL(string:countrySeletedflagUrl)!) agentViewModel.fetchAgentLocation(countryId: countrySelectedId) } } func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { URLSession.shared.dataTask(with: url) { data, response, error in completion(data, response, error) }.resume() } /** To download image through url - parameter url: url */ func downloadImage(url: URL) { getDataFromUrl(url: url) { data, response, error in guard let data = data, error == nil else { return } DispatchQueue.main.async() { let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 50)) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) let image = UIImage(data: data) imageView.center = paddingView.center imageView.image = image paddingView.addSubview(imageView) self.searchTextField.leftViewMode = UITextFieldViewMode.always self.searchTextField.leftView = paddingView } } } } extension AgentBankViewController: UITableViewDelegate, UITableViewDataSource, AgentTableViewCellDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return agentPayoutList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { self.tableRowIndex = indexPath.row agentCell = tableView.dequeueReusableCell(withIdentifier: "agentCell", for: indexPath) as? AgentTableViewCell agentCell?.layer.borderColor = UIColor(red:0.91, green:0.93, blue:0.95, alpha:1.0).cgColor agentCell?.layer.borderWidth = 2.5 agentCell?.layer.cornerRadius = 10 agentCell?.clipsToBounds = true if let name = agentPayoutList[indexPath.row].name { agentCell?.labelBranchName.text = name } if let address = agentPayoutList[indexPath.row].address { agentCell?.labelBranchAddress.text = address } if let phone = agentPayoutList[indexPath.row].phone{ agentCell?.buttonPhoneNumber.setTitle(phone, for: UIControlState.normal) }else{ agentCell?.buttonPhoneNumber.setTitle(" ", for: UIControlState.normal) } agentCell?.buttonMap?.addTarget(self, action:#selector(agentTableViewCellDidTapMap(_:)), for:.touchUpInside) return agentCell! } @objc func agentTableViewCellDidTapMap(_ sender: AgentTableViewCell) { guard let clickedCell = sender.superview?.superview?.superview as? AgentTableViewCell else { return } let clickedCellIndexPath = tableViewAgent.indexPath(for: clickedCell) selectedCell = clickedCellIndexPath?.row let storyboard = UIStoryboard.init(name: "RecipientListViewController", bundle: Bundle.main) if let agentLocationViewController = storyboard.instantiateViewController(withIdentifier: "agentLocation") as? AgentLocation { if let lat = agentPayoutList[self.tableRowIndex!].latitude{ if let lng = agentPayoutList[self.tableRowIndex!].longitude{ let latitude = String (lat) let longitude = String (lng) agentLocationViewController.latitude = CLLocationDegrees(latitude) agentLocationViewController.longitude = CLLocationDegrees(longitude)! self.navigationController!.pushViewController(agentLocationViewController, animated: true) } } else{ self.popUpMessageInfo(value: 16, title: "Location", message: "Map view is not available.") } } } func sectionIndexTitles(for tableView: UITableView) -> [String]? { return ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"] } func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { let tappedIndex = getAgentLocationAddress().index(where: {$0.prefix(1).uppercased() == title}) if tappedIndex != nil { self.previousIndex = tappedIndex! tableView.scrollToRow(at: IndexPath(row: tappedIndex!, section: 0), at: UITableViewScrollPosition.top, animated: true) } return previousIndex //Previous index is set so that in case when there is no data for selected title, the screen remains at the previous selection title } } extension AgentBankViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return getCountryList().count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return getCountryList()[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.selectedIndex = row isSelect = true } /** To display image on picker view row */ func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var myImageView: UIImageView? let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60)) let myLabel = UILabel(frame: CGRect(x: 60, y: 0, width: pickerView.bounds.width - 90, height: 60 )) myLabel.text = agentCountryList[row].country myView.addSubview(myLabel) /// Display country flag on pickerview myImageView = UIImageView(frame: CGRect(x: 0, y: 15, width: 30, height: 30)) myImageView?.sd_setImage(with:URL(string: self.agentCountryList[row].flagUrl ?? ""), placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) myView.addSubview(myImageView!) return myView } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 60 } } extension AgentBankViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { self.pickUp(textField) self.setPickerViewRowAsSelected() } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return false } func textFieldDidEndEditing(_ textField: UITextField) { } }