// // DashboardViewController.swift // LMS // // Created by Suraj Kumar Mandal on 18/08/22. // import UIKit import SideMenu import Toast_Swift class DashboardViewController: UIViewController { @IBOutlet var navigationBar: UINavigationBar! @IBOutlet var usernameLabel: UILabel! @IBOutlet var academicYearLabel: UILabel! @IBOutlet var classLabel: UILabel! @IBOutlet var divisionLabel: UILabel! @IBOutlet var typeSegmentControl: UISegmentedControl! @IBOutlet var upcomingSessionView: UIView! @IBOutlet var sessionListTableView: UITableView! @IBOutlet var viewAllSessionButton: UIButton! @IBOutlet var upcomingAssessmentView: UIView! @IBOutlet var assessmentListTableView: UITableView! @IBOutlet var viewAllAssessmentButton: UIButton! let userData = DBManager.sharedInstance.database.objects(UserDetailsModel.self) let studentData = DBManager.sharedInstance.database.objects(StudentDetailsModel.self) var viewModel = DashboardViewModel() var sessionListModel = [SessionListModel]() var assessmentListModel = [AssessmentListModel]() var expandedSections = Set() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. viewModel.delegate = self setupData() upcomingSessionView.isHidden = true upcomingAssessmentView.isHidden = true sessionListTableView.delegate = self sessionListTableView.dataSource = self assessmentListTableView.delegate = self assessmentListTableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { viewModel.getSessionList(userId: userData[0].id, interventionId: "", batchId: "", schoolId: "", interventionLevelId: "", month: getCurrentMonth()) viewModel.getAssessmentList(userId: userData[0].id, month: getCurrentMonth()) } func setupData() { navigationBar.topItem?.title = "Dashboard" usernameLabel.text = "Hi \(userData[0].name)," academicYearLabel.text = studentData[0].academicYear classLabel.text = studentData[0].standard divisionLabel.text = studentData[0].division } 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() self.assessmentListTableView.reloadData() DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { [weak self] in self?.executeRepeatedly() } } 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 formatDate(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 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 } /* // 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 segmentControllClick(_ sender: Any) { switch typeSegmentControl.selectedSegmentIndex { case 0: upcomingSessionView.isHidden = false upcomingAssessmentView.isHidden = true case 1: upcomingSessionView.isHidden = true upcomingAssessmentView.isHidden = false default: break } } @IBAction func viewAllSessionAction(_ sender: Any) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "SessionListViewController") as! SessionListViewController self.navigationController?.pushViewController(vc, animated: true) } @IBAction func viewAllAssessmentAction(_ sender: Any) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "AssessmentBeneficiaryViewController") as! AssessmentBeneficiaryViewController self.navigationController?.pushViewController(vc, animated: true) } } extension DashboardViewController: DashboardProtocol { func sessionListModel(model: [SessionListModel]) { if model.isEmpty == false { let dateSortedData = model.sorted(by: {$0.date! > $1.date!}) let timeSortedData = dateSortedData.sorted(by: {$0.startTime! > $1.startTime!}) var i = 0 for item in timeSortedData { if i < 4 { self.sessionListModel.append(item) i += 1 } } self.sessionListTableView.reloadData() self.upcomingSessionView.isHidden = false } else { self.upcomingSessionView.isHidden = true } } func assessmentListModel(model: [AssessmentListModel]) { if model.isEmpty == false { let dateSortedData = model.sorted(by: {$0.startDateTime! > $1.startDateTime!}) var i = 0 for item in dateSortedData { if i < 4 { self.assessmentListModel.append(item) i += 1 } } self.assessmentListTableView.reloadData() self.upcomingAssessmentView.isHidden = false } else { self.upcomingAssessmentView.isHidden = true } } func startLoader() { ActivityIndicator.start() } func stopLoader() { ActivityIndicator.stop() } func showError(error: String) { self.view.makeToast(error) } } extension DashboardViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == sessionListTableView { return sessionListModel.count } else { return assessmentListModel.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == sessionListTableView { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DashboardSessionListTableViewCell", for: indexPath) as? DashboardSessionListTableViewCell else { return UITableViewCell() } cell.selectionStyle = .none cell.sessionCustomView.layer.cornerRadius = 10 cell.sessionNameLabel.text = sessionListModel[indexPath.row].scheduleTitle cell.dayDateLabel.text = formattedDateFromString(dateString: sessionListModel[indexPath.row].date!, withFormat: "EEEE, MMM dd, yyyy") cell.timeLabel.text = "\(formattedTimeFromString(dateString: sessionListModel[indexPath.row].startTime!, withFormat: "HH:mm") ?? "") - \(formattedTimeFromString(dateString: sessionListModel[indexPath.row].endTime!, withFormat: "HH:mm") ?? "")" cell.joinButton.layer.cornerRadius = 5 cell.joinButton.addTarget(self, action: #selector(joinClass), for: .touchUpInside) return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DashboardAssessmentListTableViewCell", for: indexPath) as? DashboardAssessmentListTableViewCell else { return UITableViewCell() } cell.selectionStyle = .none cell.assessmentCustomView.layer.cornerRadius = 10 cell.assessmentNameLabel.text = assessmentListModel[indexPath.row].assessment?.name cell.dayDateLabel.text = " " + (formatDate(dateString: assessmentListModel[indexPath.row].startDateTime!, withFormat: "dd MMM") ?? "") + " " cell.timeLabel.text = (formattedTimeFromString(dateString: assessmentListModel[indexPath.row].startDateTime!, withFormat: "HH:mm") ?? "") + " to " + (formattedTimeFromString(dateString: assessmentListModel[indexPath.row].endDateTime!, withFormat: "HH:mm") ?? "") cell.activeStatusLabel.text = assessmentListModel[indexPath.row].assessment?.mode if assessmentListModel[indexPath.row].assessment?.mode == "Online" { cell.statusIndicatorImageView.tintColor = #colorLiteral(red: 0.3843137255, green: 0.6470588235, blue: 0.262745098, alpha: 1) cell.startButton.backgroundColor = #colorLiteral(red: 0.00400000019, green: 0.200000003, blue: 0.3919999897, alpha: 1) cell.startButton.isEnabled = true } else { cell.statusIndicatorImageView.tintColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) cell.startButton.backgroundColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1) cell.startButton.isEnabled = false } cell.startButton.tag = indexPath.row cell.startButton.addTarget(self, action: #selector(startQuiz), for: .touchUpInside) return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == sessionListTableView { UIView.animate(withDuration: 0.3) { self.sessionListTableView.performBatchUpdates(nil) } } else { UIView.animate(withDuration: 0.3) { self.assessmentListTableView.performBatchUpdates(nil) } } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if tableView == sessionListTableView { if let cell = self.sessionListTableView.cellForRow(at: indexPath) as? DashboardSessionListTableViewCell { cell.hideDetailView() } } else { if let cell = self.assessmentListTableView.cellForRow(at: indexPath) as? DashboardAssessmentListTableViewCell { cell.hideDetailView() } } } @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) } @objc func startQuiz(sender: UIButton) { 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: assessmentListModel[sender.tag].startDateTime!) let endTime = format.date(from: assessmentListModel[sender.tag].endDateTime!) if currentTime! >= startTime! && currentTime! <= endTime! { if assessmentListModel[sender.tag].assessment?.mode == "Online" { let vc = self.storyboard?.instantiateViewController(withIdentifier: "InstructionViewController") as! InstructionViewController vc.assessmentId = assessmentListModel[sender.tag].assessment?.id ?? 0 vc.assessmentName = assessmentListModel[sender.tag].assessment?.name ?? "" self.navigationController?.pushViewController(vc, animated: true) } else { let vc = self.storyboard?.instantiateViewController(withIdentifier: "OfflineAssessmentViewController") as! OfflineAssessmentViewController let fileType = assessmentListModel[sender.tag].assessment?.fileType let fileExtension = fileType!.components(separatedBy: "/")[1] vc.fileExtension = fileExtension vc.assessmentName = assessmentListModel[sender.tag].assessment?.name ?? "" vc.assessmentId = assessmentListModel[sender.tag].assessment?.id ?? 0 vc.fileId = assessmentListModel[sender.tag].assessment?.fileId ?? "" self.navigationController?.pushViewController(vc, animated: true) } } else if currentTime! >= startTime! && currentTime! >= endTime! { Alert.showAlert(on: self, with: "Times Up", message: "Exam is already finished!") } else { Alert.showAlert(on: self, with: "Upcoming", message: "Exam will start on \(formattedDateFromString(dateString: assessmentListModel[sender.tag].startDateTime!, withFormat: "dd-MMM-yyyy hh:mm a") ?? "")") } } }