// // SessionListViewController.swift // LMS // // Created by Suraj Kumar Mandal on 24/08/22. // import UIKit import Toast_Swift import SideMenu class SessionListViewController: UIViewController { @IBOutlet var navigationBar: UINavigationBar! @IBOutlet var contentScrollView: UIScrollView! @IBOutlet var customView: UIView! // @IBOutlet var interventionLabel: UILabel! // @IBOutlet var interventionTF: UITextField! // @IBOutlet var interventionLevelLabel: UILabel! // @IBOutlet var interventionLevelTF: UITextField! // @IBOutlet var batchLabel: UILabel! // @IBOutlet var batchTF: UITextField! @IBOutlet var monthYearLabel: UILabel! @IBOutlet var monthYearTF: UITextField! @IBOutlet var sessionListTableView: UITableView! @IBOutlet var filterButton: UIButton! @IBOutlet var sessionTableHeightConstraint: NSLayoutConstraint! var viewModel = SessionListViewModel() var sessionListModel = [SessionListModel]() var interventionModel = [SessionInterventionModel]() var interventionLevelModel = [InterventionLevel]() var batchListModel = [BatchListModel]() fileprivate let picker = ToolbarPickerView() var activeTextField = 0 let userData = DBManager.sharedInstance.database.objects(UserDetailsModel.self) var interventionId = Int() var batchId = Int() var interventionLevelId = Int() var monthYear = String() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUI() viewModel.delegate = self sessionListTableView.delegate = self sessionListTableView.dataSource = self sessionListTableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) //getInterventionList() // Set UITableViewAutomaticDimension for automatic cell height calculation. sessionListTableView.rowHeight = UITableView.automaticDimension sessionListTableView.estimatedRowHeight = 240 // Estimated average cell height, adjust as needed. } override func viewWillAppear(_ animated: Bool) { getSessionList(month: getCurrentMonth()) createPickerView() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if(keyPath == "contentSize") { if let newvalue = change?[.newKey] { DispatchQueue.main.async { let newsize = newvalue as! CGSize self.sessionTableHeightConstraint.constant = newsize.height } } } } func setupUI() { navigationBar.topItem?.title = "Session List" // Hide unused fields // interventionLabel.isHidden = true // interventionTF.isHidden = true // interventionLevelLabel.isHidden = true // interventionLevelTF.isHidden = true // batchLabel.isHidden = true // batchTF.isHidden = true customView.isHidden = false customView.layer.cornerRadius = 10 // interventionTF.isUserInteractionEnabled = true // interventionLevelTF.isUserInteractionEnabled = false // batchTF.isUserInteractionEnabled = false filterButton.layer.cornerRadius = filterButton.frame.size.height / 2 let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-yyyy" let currentDate = Date() let formattedDate = dateFormatter.string(from: currentDate) // Set the formatted date as the text of the UITextField monthYearTF.text = formattedDate } func createPickerView() { monthYearTF.delegate = self self.monthYearTF.datePicker(target: self, doneAction: #selector(doneAction), cancelAction: #selector(cancelAction), datePickerMode: .date) // //1 // self.interventionTF.delegate = self // self.interventionTF.inputView = self.picker // self.interventionTF.inputAccessoryView = self.picker.toolbar // //2 // self.interventionLevelTF.delegate = self // self.interventionLevelTF.inputView = self.picker // self.interventionLevelTF.inputAccessoryView = self.picker.toolbar // //3 // self.batchTF.delegate = self // self.batchTF.inputView = self.picker // self.batchTF.inputAccessoryView = self.picker.toolbar // // self.picker.delegate = self // self.picker.dataSource = self // self.picker.toolbarDelegate = self } @objc func cancelAction() { self.monthYearTF.resignFirstResponder() } @objc func doneAction() { if let datePickerView = self.monthYearTF.inputView as? UIDatePicker { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-yyyy" let dateString = dateFormatter.string(from: datePickerView.date) self.monthYearTF.text = dateString print(datePickerView.date) print(dateString) self.getSessionList(month: self.monthYearTF.text ?? "") self.monthYearTF.resignFirstResponder() } } func getSessionList(month:String) { if Reachability.isConnectedToNetwork() { viewModel.getSessionList(userId: userData[0].id, interventionId: "", batchId: "", schoolId: "", interventionLevelId: "", month: month) } else { Alert.showInternetFailureAlert(on: self) } } func getInterventionList() { if Reachability.isConnectedToNetwork() { viewModel.getSessionIntervention() } else { Alert.showInternetFailureAlert(on: self) } } func formattedDateFromString(dateString: String, withFormat format: String) -> String? { let inputFormatter = DateFormatter() inputFormatter.dateFormat = "yyyy-MM-dd" if let date = inputFormatter.date(from: dateString) { let outputFormatter = DateFormatter() outputFormatter.dateFormat = format return outputFormatter.string(from: date) } return nil } func formattedTimeFromString(dateString: String, withFormat format: String) -> String? { let inputFormatter = DateFormatter() inputFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" if let date = inputFormatter.date(from: dateString) { let outputFormatter = DateFormatter() outputFormatter.dateFormat = format outputFormatter.timeStyle = .short return outputFormatter.string(from: date) } return nil } func getCurrentMonth() -> String { let date = Date() let format = DateFormatter() format.dateFormat = "MM-yyyy" let formattedMonth = format.string(from: date) return formattedMonth } private func executeRepeatedly() { // put your code here self.sessionListTableView.reloadData() DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { [weak self] in self?.executeRepeatedly() } } /* // 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 sideMenuAction(_ sender: UIBarButtonItem) { let menu = storyboard!.instantiateViewController(withIdentifier: "SideMenuNavigationController") as! SideMenuNavigationController present(menu, animated: true, completion: nil) } @IBAction func filterAction(_ sender: Any) { if customView.isHidden == true { customView.isHidden = false //contentScrollView.scrollToTop() contentScrollView.scrollViewToTop(customView) } else { customView.isHidden = true } } } extension SessionListViewController: SessionListProtocol { func startLoader() { ActivityIndicator.start() } func stopLoader() { ActivityIndicator.stop() } func showError(error: String) { self.view.makeToast(error) } func sessionListModel(model: [SessionListModel]) { let dateSortedData = model.sorted(by: {$0.date! > $1.date!}) let timeSortedData = dateSortedData.sorted(by: {$0.startTime! > $1.startTime!}) self.sessionListModel = timeSortedData self.executeRepeatedly() } func interventionModel(model: [SessionInterventionModel]) { self.interventionModel = model //interventionLevelTF.isUserInteractionEnabled = true } func interventionLevelModel(model: [InterventionLevel]) { self.interventionLevelModel = model //batchTF.isUserInteractionEnabled = true } func batchListModel(model: [BatchListModel]) { self.batchListModel = model } } //extension SessionListViewController: 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 interventionModel.count // case 2: // return interventionLevelModel.count // case 3: // return batchListModel.count // default: // return 0 // // } // } // // func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { // switch activeTextField{ // case 1: // return interventionModel[row].interventionName // case 2: // return interventionLevelModel[row].interventionLevels // case 3: // return batchListModel[row].batchName // default: // return "" // } // } // // func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // switch activeTextField{ // case 1: // //interventionTF.text = interventionModel[row].interventionName // break // case 2: // //interventionLevelTF.text = interventionLevelModel[row].interventionLevels // break // case 3: // //batchTF.text = batchListModel[row].batchName // break // default: // break // } // } //} //extension SessionListViewController: UITextFieldDelegate { // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // switch textField { // case interventionTF: // return false // case interventionLevelTF: // return false // case batchTF: // return false // default: // return true // } // } // // // when user select a textfield, this method will be called // func textFieldDidBeginEditing(_ textField: UITextField) { // switch textField { // case interventionTF: // activeTextField = 1 // picker.reloadAllComponents() // case interventionLevelTF: // activeTextField = 2 // picker.reloadAllComponents() // case batchTF: // activeTextField = 3 // picker.reloadAllComponents() // default: // activeTextField = 0 // } // } //} //extension SessionListViewController: ToolbarPickerViewDelegate { // func didTapDone() { // switch activeTextField { // case 1: // let row = self.picker.selectedRow(inComponent: 0) // self.picker.selectRow(row, inComponent: 0, animated: false) // self.interventionTF.text = interventionModel[row].interventionName // self.interventionId = interventionModel[row].id ?? 0 // if Reachability.isConnectedToNetwork() { // viewModel.getSessionList(userId: userData[0].id, interventionId: self.interventionId, batchId: "", schoolId: "", interventionLevelId: "", month: getCurrentMonth()) // } // self.interventionTF.resignFirstResponder() // if Reachability.isConnectedToNetwork() { // self.viewModel.getInterventionLevel(id: interventionModel[row].id ?? 0) // } // case 2: // let row = self.picker.selectedRow(inComponent: 0) // self.picker.selectRow(row, inComponent: 0, animated: false) // self.interventionLevelTF.text = interventionLevelModel[row].interventionLevels // self.interventionLevelId = interventionLevelModel[row].id ?? 0 // if Reachability.isConnectedToNetwork() { // viewModel.getSessionList(userId: userData[0].id, interventionId: self.interventionId, batchId: "", schoolId: "", interventionLevelId: self.interventionLevelId, month: getCurrentMonth()) // } // self.interventionLevelTF.resignFirstResponder() // if Reachability.isConnectedToNetwork() { // self.viewModel.getBatchList() // } // case 3: // let row = self.picker.selectedRow(inComponent: 0) // self.picker.selectRow(row, inComponent: 0, animated: false) // self.batchTF.text = batchListModel[row].batchName ?? "" // self.batchId = batchListModel[row].id ?? 0 // if Reachability.isConnectedToNetwork() { // viewModel.getSessionList(userId: userData[0].id, interventionId: self.interventionId, batchId: self.batchId, schoolId: "", interventionLevelId: self.interventionLevelId, month: getCurrentMonth()) // } // self.batchTF.resignFirstResponder() // default: // return // } // } // func didTapCancel() { // switch activeTextField { // case 1: // self.interventionTF.text = nil // self.interventionTF.resignFirstResponder() // case 2: // self.interventionLevelTF.text = nil // self.interventionLevelTF.resignFirstResponder() // case 3: // self.batchTF.text = nil // self.batchTF.resignFirstResponder() // default: // return // } // } //} extension SessionListViewController: UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegateFlowLayout { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sessionListModel.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "SessionListTableViewCell", for: indexPath) as? SessionListTableViewCell else { return UITableViewCell() } cell.listCustomView.layer.cornerRadius = 10 cell.listCustomView.layer.borderWidth = 1 cell.listCustomView.layer.borderColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) cell.serialNumberLabel.text = "\(indexPath.row + 1)" cell.meetingNameLabel.text = sessionListModel[indexPath.row].scheduleTitle cell.batchLabel.text = sessionListModel[indexPath.row].batchName cell.teacherLabel.text = "Teacher: \(sessionListModel[indexPath.row].teacherFirstName ?? "") \(sessionListModel[indexPath.row].teacherLastName ?? "")" cell.interventionNameLabel.text = "Intervention Name: \(sessionListModel[indexPath.row].interventionName ?? "")" cell.dateLabel.text = " " + (formattedDateFromString(dateString: sessionListModel[indexPath.row].date!, withFormat: "dd MMM") ?? "") + " " cell.timeLabel.text = (formattedTimeFromString(dateString: sessionListModel[indexPath.row].startTime!, withFormat: "HH:mm") ?? "") + " to " + (formattedTimeFromString(dateString: sessionListModel[indexPath.row].endTime!, withFormat: "HH:mm") ?? "") cell.joinClassButton.layer.cornerRadius = 5 if sessionListModel[indexPath.row].offline == true { cell.activeStatusLabel.text = "Online" cell.activeIndicatorImageView.tintColor = #colorLiteral(red: 0.3843137255, green: 0.6470588235, blue: 0.262745098, alpha: 1) cell.joinClassButton.isHidden = false } else { cell.activeStatusLabel.text = "Offline" cell.activeIndicatorImageView.tintColor = #colorLiteral(red: 0.9098039216, green: 0.2980392157, blue: 0.2470588235, alpha: 1) cell.joinClassButton.isHidden = true } let date = Date() let format = DateFormatter() format.dateFormat = "yyyy-MM-dd HH:mm:ss" let time = format.string(from: date) let currentTime = format.date(from: time) let startTime = format.date(from: sessionListModel[indexPath.row].startTime!)?.addingTimeInterval(TimeInterval(10.0 * 60.0)) let endTime = format.date(from: sessionListModel[indexPath.row].endTime!)?.addingTimeInterval(TimeInterval(20.0 * 60.0)) if currentTime! > startTime! && currentTime! < endTime! { cell.joinClassButton.backgroundColor = #colorLiteral(red: 0.00400000019, green: 0.200000003, blue: 0.3919999897, alpha: 1) cell.joinClassButton.tag = indexPath.row cell.joinClassButton.addTarget(self, action: #selector(joinClass), for: .touchUpInside) } else { cell.joinClassButton.backgroundColor = UIColor.lightGray cell.joinClassButton.isUserInteractionEnabled = false } return cell } @objc func joinClass(sender: UIButton){ print(sender.tag) guard let url = URL(string: sessionListModel[sender.tag].link ?? "") else { return } print(sessionListModel[sender.tag].link ?? "") UIApplication.shared.open(url) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } extension SessionListViewController: UITextFieldDelegate { // MARK: - UITextFieldDelegate methods func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { switch textField { case monthYearTF: return false default: return true } } }