// // UserDetailsViewController.swift // Learn Genie // // Created by Suraj Kumar Mandal on 03/09/21. // import UIKit import Toast_Swift import Alamofire class UserDetailsViewController: UIViewController { @IBOutlet var nameLabel: UILabel! @IBOutlet var nameTF: UITextField! @IBOutlet var emailLabel: UILabel! @IBOutlet var emailTF: UITextField! @IBOutlet var dobLabel: UILabel! @IBOutlet var dobTF: UITextField! @IBOutlet var genderLabel: UILabel! @IBOutlet var genderTF: UITextField! @IBOutlet var mobileLabel: UILabel! @IBOutlet var mobileTF: UITextField! @IBOutlet var stateLabel: UILabel! @IBOutlet var stateTF: UITextField! @IBOutlet var districtLabel: UILabel! @IBOutlet var districtTF: UITextField! @IBOutlet var submitButton: CustomButton! var viewModel = UserDetailsViewModel() let stateData = DBManager.sharedInstance.database.objects(StateModel.self) let districtData = DBManager.sharedInstance.database.objects(DistrictModel.self) let userData = UserDefaults.standard.dictionary(forKey: Constant.userData) let genderData = [String](arrayLiteral: "Male", "Female", "Third Gender", "Will not specify") var pageMode = String() //Register / Profile fileprivate let customPicker = ToolbarPickerView() var stateArray = [String]() var stateIdArray = [Int]() var districtArray = [String]() var stateId = 1 //default var districtId = 1 //default var gender = "Will not specify" var dateOfBirth = "01/01/2021" var mobile = "9999999999" var activeTextField = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. viewModel.delegate = self ApiManager.generateCookie() print(pageMode) } override func viewWillAppear(_ animated: Bool) { setupUI() setupUserData() } func setupUI() { let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) view.addGestureRecognizer(tap) } func setupUserData() { //Set text field title name nameLabel.text = Helper.translateText(inputText: "Enter Name") emailLabel.text = Helper.translateText(inputText: "Email") dobLabel.text = Helper.translateText(inputText: "Enter Date of Birth") genderLabel.text = Helper.translateText(inputText: "Select Gender") mobileLabel.text = Helper.translateText(inputText: "Mobile") stateLabel.text = Helper.translateText(inputText: "Select State") districtLabel.text = Helper.translateText(inputText: "Select District") if pageMode == "Profile" { submitButton.setTitle(Helper.translateText(inputText: "UPDATE"), for: .normal) } else { submitButton.setTitle(Helper.translateText(inputText: "SUBMIT"), for: .normal) } //Set text field data if pageMode == "Profile" { let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self) if let row = userModelDB.firstIndex(where: {$0.email == self.userData?["email"] as? String}) { nameTF.text = userModelDB[row].name emailTF.text = userModelDB[row].email let dateString = userModelDB[row].dateOfBirth let requiredFormat = dateString.toDateString(inputDateFormat: "yyyy-MM-dd'T'HH:mm:ssZ", ouputDateFormat: Constant.dateFormat) dobTF.text = requiredFormat genderTF.text = userModelDB[row].gender mobileTF.text = userModelDB[row].mobile stateTF.text = getStateName(id: userModelDB[row].stateId) self.stateId = userModelDB[row].stateId districtTF.text = getDistrictName(id: userModelDB[row].districtId) self.districtId = userModelDB[row].districtId } } nameTF.text = userData?["name"] as? String emailTF.text = userData?["email"] as? String dobTF.datePicker(target: self, doneAction: #selector(doneAction), cancelAction: #selector(cancelAction), datePickerMode: .date) createPickerView() nameTF.delegate = self emailTF.delegate = self dobTF.delegate = self genderTF.delegate = self mobileTF.delegate = self stateTF.delegate = self districtTF.delegate = self districtTF.isUserInteractionEnabled = false stateArray.removeAll() stateIdArray.removeAll() getState() } @objc func dismissKeyboard() { self.view.endEditing(true) } func createPickerView() { self.genderTF.inputView = self.customPicker self.genderTF.inputAccessoryView = self.customPicker.toolbar self.stateTF.inputView = self.customPicker self.stateTF.inputAccessoryView = self.customPicker.toolbar self.districtTF.inputView = self.customPicker self.districtTF.inputAccessoryView = self.customPicker.toolbar self.customPicker.delegate = self self.customPicker.dataSource = self self.customPicker.toolbarDelegate = self } @objc func cancelAction() { self.dobTF.resignFirstResponder() } @objc func doneAction() { if let datePickerView = self.dobTF.inputView as? UIDatePicker { let dateFormatter = DateFormatter() dateFormatter.dateFormat = Constant.dateFormat let dateString = dateFormatter.string(from: datePickerView.date) self.dobTF.text = dateString self.dateOfBirth = dateString print(datePickerView.date) print(dateString) self.dobTF.resignFirstResponder() } } func getStateName(id:Int) -> String { var stateName = String() if let row = stateData.firstIndex(where: {$0.id == id}) { stateName = stateData[row].stateName } return stateName } func getDistrictName(id:Int) -> String { var districtName = String() if let row = districtData.firstIndex(where: {$0.id == id}) { districtName = districtData[row].districtName } return districtName } func getState() { for state in stateData { let id = state.id let name = state.stateName self.stateIdArray.append(id) self.stateArray.append(name) } } func getDistrict(stateId:Int) { for district in districtData { if district.stateId == stateId { let name = district.districtName self.districtArray.append(name) } } } func getStateId(name: String) -> Int { var id = Int() for state in stateData { if name == state.stateName { id = state.id } } return id } func getDistrictId(name: String) -> Int { var id = Int() for district in districtData { if name == district.districtName { id = district.id } } return id } func checkValidation() { if nameTF.text?.isEmpty == true { self.view.makeToast(Helper.translateText(inputText: "Enter a valid name, 3 or more characters long")) } else if emailTF.text?.isEmpty == true && emailTF.text?.isValidEmail == false { self.view.makeToast(Helper.translateText(inputText: "Enter valid email")) } // else if dobTF.text?.isEmpty == true { // self.view.makeToast(Helper.translateText(inputText: "Select your date of birth")) // } // else if genderTF.text?.isEmpty == true { // self.view.makeToast(Helper.translateText(inputText: "Select your gender")) // } // else if mobileTF.text?.isEmpty == true { // self.view.makeToast(Helper.translateText(inputText: "Enter Mobile Number")) // } // else if mobileTF.text?.count != 10 { // self.view.makeToast(Helper.translateText(inputText: "Enter Valid Mobile Number")) // } // else if stateTF.text?.isEmpty == true { // self.view.makeToast(Helper.translateText(inputText: "Select your state")) // } // else if districtTF.text?.isEmpty == true { // self.view.makeToast(Helper.translateText(inputText: "Select your district")) // } else { if pageMode == "Profile" { updateStudent() } else { saveStudent() } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ @IBAction func submitButtonAction(_ sender: Any) { if Reachability.isConnectedToNetwork() { checkValidation() } else { Alert.showInternetFailureAlert(on: self) } } } extension UserDetailsViewController: UIPickerViewDelegate, UIPickerViewDataSource { // MARK: UIPickerView Delegation func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch activeTextField { case 1: return genderData.count case 2: return stateArray.count case 3: return districtArray.count default: return districtArray.count } } func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch activeTextField{ case 1: return genderData[row] case 2: return stateArray[row] case 3: return districtArray[row] default: return districtArray[row] } } func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch activeTextField{ case 1: genderTF.text = genderData[row] break case 2: stateTF.text = stateArray[row] break case 3: districtTF.text = districtArray[row] break default: districtTF.text = districtArray[row] break } } } extension UserDetailsViewController: UITextFieldDelegate { // when user select a textfield, this method will be called func textFieldDidBeginEditing(_ textField: UITextField) { switch textField { case genderTF: activeTextField = 1 customPicker.reloadAllComponents() case stateTF: activeTextField = 2 customPicker.reloadAllComponents() case districtTF: activeTextField = 3 customPicker.reloadAllComponents() default: activeTextField = 0 } } } extension UserDetailsViewController: ToolbarPickerViewDelegate { func didTapDone() { switch activeTextField { case 1: let row = self.customPicker.selectedRow(inComponent: 0) self.customPicker.selectRow(row, inComponent: 0, animated: false) self.genderTF.text = self.genderData[row] self.genderTF.resignFirstResponder() case 2: let row = self.customPicker.selectedRow(inComponent: 0) self.customPicker.selectRow(row, inComponent: 0, animated: false) self.stateTF.text = self.stateArray[row] districtTF.isUserInteractionEnabled = true self.districtTF.text = nil districtArray.removeAll() getDistrict(stateId: self.stateIdArray[row]) self.stateId = getStateId(name: self.stateArray[row]) self.stateTF.resignFirstResponder() case 3: let row = self.customPicker.selectedRow(inComponent: 0) self.customPicker.selectRow(row, inComponent: 0, animated: false) self.districtTF.text = self.districtArray[row] self.districtId = getDistrictId(name: self.districtArray[row]) self.districtTF.resignFirstResponder() default: return } } func didTapCancel() { switch activeTextField{ case 1: self.genderTF.text = nil self.genderTF.resignFirstResponder() case 2: self.stateTF.text = nil self.stateTF.resignFirstResponder() case 3: self.districtTF.text = nil self.districtTF.resignFirstResponder() default: return } } } extension UserDetailsViewController { func saveStudent() { ActivityIndicator.start(style: .large, backColor: UIColor.black.withAlphaComponent(0.5), baseColor: UIColor.white) let topicData = DBManager.sharedInstance.database.objects(TopicModel.self) if topicData.count != 0 { let topicId = topicData[0].id let levelId = topicData[0].levelId let url = "\(ApiUrl.BASE_URL + ApiUrl.API_STUDENT)/save.json" print(url) let userIdentifier = UserDefaultsConstant.getValueFromUserDefults(for: Constant.userIdentifier) ?? "" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) if mobileTF.text?.isEmpty == false { self.mobile = mobileTF.text! } else if genderTF.text?.isEmpty == false { self.gender = genderTF.text! } else if dobTF.text?.isEmpty == false { self.dateOfBirth = dobTF.text! } let params: Parameters? params = [ "appleUserIdentifier" : userIdentifier, "name" : nameTF.text ?? "", "mobile" : mobile, "email" : emailTF.text ?? "", "username" : emailTF.text?.stringBefore("@") ?? "", "password" : emailTF.text?.stringBefore("@") ?? "", "gender" : gender, "dateOfBirth" : dateOfBirth, "state" : self.stateId, "district" : self.districtId, "topic" : topicId, "level" : levelId, "role" : 2 ] print(params!) AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(let value): ActivityIndicator.stop() print(value) let userData = value as! NSDictionary let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber; let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber; let dateCreated = userData.value(forKey: "dateCreated") as? String ?? ""; let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? ""; let district = userData.value(forKey: "district") as? NSObject; let districtId = district?.value(forKey: "id") as! NSNumber; let email = userData.value(forKey: "email") as? String ?? ""; let enabled = userData.value(forKey: "enabled") as! NSNumber; let gender = userData.value(forKey: "gender") as? String ?? ""; let id = userData.value(forKey: "id") as! NSNumber; let level = userData.value(forKey: "level") as? NSObject; let levelId = level?.value(forKey: "id") as! NSNumber; let mobile = userData.value(forKey: "mobile") as? String ?? ""; let name = userData.value(forKey: "name") as? String ?? ""; let password = userData.value(forKey: "password") as? String ?? ""; let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber; let role = userData.value(forKey: "role") as? NSObject; let roleId = role?.value(forKey: "id") as! NSNumber; let state = userData.value(forKey: "state") as? NSObject; let stateId = state?.value(forKey: "id") as! NSNumber; let topic = userData.value(forKey: "topic") as? NSObject; let topicId = topic?.value(forKey: "id") as! NSNumber; let username = userData.value(forKey: "username") as? String ?? ""; let appleUserIdentifier = userData.value(forKey: "appleUserIdentifier") as? String ?? ""; var userModel = [UserDetailsModel]() let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: appleUserIdentifier) userModel.append(newUserModel) DBManager.sharedInstance.addData(objs: userModel) let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self) print("user count") print(userModelDB.count) UserDefaultsConstant.setIntValueInUserDefaults(objValue: Int(truncating: id), for: Constant.studentId) //Navigate to Home DispatchQueue.main.async { let loaderVC = self.storyboard?.instantiateViewController(withIdentifier:"LoadingAnimationViewController" ) as! LoadingAnimationViewController self.navigationController?.pushViewController(loaderVC, animated: true) } case .failure(let error): ActivityIndicator.stop() print(error) } } } } func updateStudent() { ActivityIndicator.start(style: .large, backColor: UIColor.black.withAlphaComponent(0.5), baseColor: UIColor.white) let topicData = DBManager.sharedInstance.database.objects(TopicModel.self) let studentId = UserDefaultsConstant.getIntValueFromUserDefults(for: Constant.studentId) as! Int if topicData.count != 0 { let topicId = topicData[0].id let levelId = topicData[0].levelId let url = "\(ApiUrl.BASE_URL + ApiUrl.API_STUDENT)/update.json" print(url) let userIdentifier = UserDefaultsConstant.getValueFromUserDefults(for: Constant.userIdentifier) ?? "" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) let params: Parameters? params = [ "appleUserIdentifier" : userIdentifier, "id" : studentId, "name" : nameTF.text ?? "", "mobile" : mobileTF.text ?? "", "email" : emailTF.text ?? "", "username" : emailTF.text?.stringBefore("@") ?? "", "password" : emailTF.text?.stringBefore("@") ?? "", "gender" : genderTF.text ?? "", "dateOfBirth" : dobTF.text ?? "", "state" : self.stateId, "district" : self.districtId, "topic" : topicId, "level" : levelId, "role" : 2 ] print(params!) AF.request(url, method: .put, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(let value): ActivityIndicator.stop() print(value) let userData = value as! NSDictionary let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber; let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber; let dateCreated = userData.value(forKey: "dateCreated") as? String ?? ""; let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? ""; let district = userData.value(forKey: "district") as? NSObject; let districtId = district?.value(forKey: "id") as! NSNumber; let email = userData.value(forKey: "email") as? String ?? ""; let enabled = userData.value(forKey: "enabled") as! NSNumber; let gender = userData.value(forKey: "gender") as? String ?? ""; let id = userData.value(forKey: "id") as! NSNumber; let level = userData.value(forKey: "level") as? NSObject; let levelId = level?.value(forKey: "id") as! NSNumber; let mobile = userData.value(forKey: "mobile") as? String ?? ""; let name = userData.value(forKey: "name") as? String ?? ""; let password = userData.value(forKey: "password") as? String ?? ""; let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber; let role = userData.value(forKey: "role") as? NSObject; let roleId = role?.value(forKey: "id") as! NSNumber; let state = userData.value(forKey: "state") as? NSObject; let stateId = state?.value(forKey: "id") as! NSNumber; let topic = userData.value(forKey: "topic") as? NSObject; let topicId = topic?.value(forKey: "id") as! NSNumber; let username = userData.value(forKey: "username") as? String ?? ""; let appleUserIdentifier = userData.value(forKey: "appleUserIdentifier") as? String ?? ""; var userModel = [UserDetailsModel]() let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: appleUserIdentifier) DBManager.sharedInstance.deleteFromDb(object: userModel) userModel.append(newUserModel) DBManager.sharedInstance.addData(objs: userModel) let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self) print("user count") print(userModelDB.count) //Navigate to Home DispatchQueue.main.async { //self.dismiss(animated: true, completion: nil) let homeVC = self.storyboard?.instantiateViewController(withIdentifier:"DashboardViewController" ) as! DashboardViewController self.navigationController?.pushViewController(homeVC, animated: true) } case .failure(let error): ActivityIndicator.stop() print(error) self.showToastMessage(message: Helper.translateText(inputText: "Failed to update profile data, please try again later")) } } } } } extension UserDetailsViewController : UserDetailsViewProtocol { func showAlert(title: String, message: String) { Alert.showAlert(on: self, with: title, message: message) } func stopActivityIndicator() { //activityIndicator.stopAnimating() } func showToastMessage(message: String) { self.view.makeToast(message) } }