<commit_before>/*******************************************************************************
 * Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package org.sakaiproject.tool.gradebook.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord;
import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.gradebook.AbstractGradeRecord;
import org.sakaiproject.tool.gradebook.Assignment;
import org.sakaiproject.tool.gradebook.AssignmentGradeRecord;
import org.sakaiproject.tool.gradebook.Category;
import org.sakaiproject.tool.gradebook.CourseGrade;
import org.sakaiproject.tool.gradebook.CourseGradeRecord;
import org.sakaiproject.tool.gradebook.GradableObject;
import org.sakaiproject.tool.gradebook.jsf.FacesUtil;

/**
 * Provides data for the instructor's view of a student's grades in the gradebook.
 */
public class InstructorViewBean extends ViewByStudentBean implements Serializable {
	private static Log logger = LogFactory.getLog(InstructorViewBean.class);

	private EnrollmentRecord previousStudent;
	private EnrollmentRecord nextStudent;
	private EnrollmentRecord currentStudent;
	
	private String studentEmailAddress;
	private String studentSections;
	
	private List orderedEnrollmentList;

	// parameters passed to the page
	private String returnToPage;
	private String assignmentId; // for returning to specific gradebook item

	private static final String ROSTER_PAGE = "roster";
	private static final String ASSIGN_DETAILS_PAGE = "assignmentDetails";

	/**
	 * @see org.sakaiproject.tool.gradebook.ui.InitializableBean#init()
	 */
	public void init() {
		previousStudent = null;
		nextStudent = null;
		studentSections = null;

		String sortByCol = getSortColumn();
		boolean sortAsc = isSortAscending();

		setIsInstructorView(true);

		if (getStudentUid() != null) {
			super.init();

			studentEmailAddress = getUserDirectoryService().getUserEmailAddress(getStudentUid());
			studentSections = getStudentSectionsForDisplay();

			// set up the "next" and "previous" student navigation
			// TODO preserve filter/sort status from originating page
			if (orderedEnrollmentList == null) {
				orderedEnrollmentList = new ArrayList();
				if (returnToPage.equals(ROSTER_PAGE)) {
					super.setSelectedSectionFilterValue(getPreferencesBean().getRosterTableSectionFilter());
					maxDisplayedScoreRows = 0;
					orderedEnrollmentList = getOrderedEnrolleesFromRosterPage();
				} else if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) {
					super.setSelectedSectionFilterValue(getPreferencesBean().getAssignmentDetailsTableSectionFilter());
					orderedEnrollmentList = getOrderedEnrolleesFromAssignDetailsPage();
				}
			}

			if (orderedEnrollmentList != null && orderedEnrollmentList.size() > 1) {
				int index = 0;
				while (index < orderedEnrollmentList.size()) {
					EnrollmentRecord enrollee = (EnrollmentRecord)orderedEnrollmentList.get(index);
					if (enrollee.getUser().getUserUid().equals(getStudentUid())) {
						currentStudent = enrollee;
						if (index-1 >= 0) {
							previousStudent = (EnrollmentRecord) orderedEnrollmentList.get(index-1);
						}
						if (index+1 < orderedEnrollmentList.size()) {
							nextStudent = (EnrollmentRecord) orderedEnrollmentList.get(index+1);
						}
						break;
					}
					index++;
				}
			}

			setSortColumn(sortByCol);
			setSortAscending(sortAsc);

		}
	}

	// Navigation
	public EnrollmentRecord getPreviousStudent() {
		return previousStudent;
	}
	public EnrollmentRecord getNextStudent() {
		return nextStudent;
	}
	
	public boolean isFirst() {
		return previousStudent == null;
	}
	public boolean isLast() {
		return nextStudent == null;
	}
	
	public EnrollmentRecord getCurrentStudent() {
		return currentStudent;
	}

	/**
	 * @return text for "Return to" button
	 */
	public String getReturnToPageButtonName() {
		String pageTitle;
		if (ASSIGN_DETAILS_PAGE.equals(returnToPage))
			pageTitle = getLocalizedString("assignment_details_page_title");
		else
			pageTitle = getLocalizedString("roster_page_title");

		return getLocalizedString("inst_view_return_to", new String[] {pageTitle});
	}
	
	/**
	 * 
	 * @return page title of originating page
	 */
	public String getReturnToPageName() {
		if (returnToPage.equals(ASSIGN_DETAILS_PAGE))
			return getLocalizedString("assignment_details_page_title");
		else
			return getLocalizedString("roster_page_title");
	}
	
	/**
	 * 
	 * @return comma-separated string of user's section/group memberships
	 */
	public String getStudentSections() {
		return studentSections;
	}
	
    /**
     * @return studentEmailAddress
     */
    public String getStudentEmailAddress() {
        return studentEmailAddress;
    }

	/**
	 * Action listener to view a different student
	 */
	public void processStudentUidChange(ActionEvent event) {
		Map params = FacesUtil.getEventParameterMap(event);
		if (logger.isDebugEnabled()) 
			logger.debug("processStudentUidChange params=" + params + ", current studentUid=" + getStudentUid());
		String idParam = (String)params.get("studentUid");
		if (idParam != null) {
			setStudentUid(idParam);
		}
		processUpdateScoresForPreNextStudent();
	}
	
	public void processUpdateScoresForPreNextStudent() {
		try {
			saveScoresWithoutConfirmation();
		} catch (StaleObjectModificationException e) {
			FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure"));
		}
	}
	
	/**<commit_msg>SAK-16395 - Widget on individual grade screen should save grades when clicking Next & Previous student - bug fix<commit_after>/*******************************************************************************
 * Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package org.sakaiproject.tool.gradebook.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord;
import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.gradebook.AbstractGradeRecord;
import org.sakaiproject.tool.gradebook.Assignment;
import org.sakaiproject.tool.gradebook.AssignmentGradeRecord;
import org.sakaiproject.tool.gradebook.Category;
import org.sakaiproject.tool.gradebook.CourseGrade;
import org.sakaiproject.tool.gradebook.CourseGradeRecord;
import org.sakaiproject.tool.gradebook.GradableObject;
import org.sakaiproject.tool.gradebook.jsf.FacesUtil;

/**
 * Provides data for the instructor's view of a student's grades in the gradebook.
 */
public class InstructorViewBean extends ViewByStudentBean implements Serializable {
	private static Log logger = LogFactory.getLog(InstructorViewBean.class);

	private EnrollmentRecord previousStudent;
	private EnrollmentRecord nextStudent;
	private EnrollmentRecord currentStudent;
	
	private String studentEmailAddress;
	private String studentSections;
	
	private List orderedEnrollmentList;

	// parameters passed to the page
	private String returnToPage;
	private String assignmentId; // for returning to specific gradebook item

	private static final String ROSTER_PAGE = "roster";
	private static final String ASSIGN_DETAILS_PAGE = "assignmentDetails";

	/**
	 * @see org.sakaiproject.tool.gradebook.ui.InitializableBean#init()
	 */
	public void init() {
		previousStudent = null;
		nextStudent = null;
		studentSections = null;

		String sortByCol = getSortColumn();
		boolean sortAsc = isSortAscending();

		setIsInstructorView(true);

		if (getStudentUid() != null) {
			super.init();

			studentEmailAddress = getUserDirectoryService().getUserEmailAddress(getStudentUid());
			studentSections = getStudentSectionsForDisplay();

			// set up the "next" and "previous" student navigation
			// TODO preserve filter/sort status from originating page
			if (orderedEnrollmentList == null) {
				orderedEnrollmentList = new ArrayList();
				if (returnToPage.equals(ROSTER_PAGE)) {
					super.setSelectedSectionFilterValue(getPreferencesBean().getRosterTableSectionFilter());
					maxDisplayedScoreRows = 0;
					orderedEnrollmentList = getOrderedEnrolleesFromRosterPage();
				} else if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) {
					super.setSelectedSectionFilterValue(getPreferencesBean().getAssignmentDetailsTableSectionFilter());
					orderedEnrollmentList = getOrderedEnrolleesFromAssignDetailsPage();
				}
			}

			if (orderedEnrollmentList != null && orderedEnrollmentList.size() > 1) {
				int index = 0;
				while (index < orderedEnrollmentList.size()) {
					EnrollmentRecord enrollee = (EnrollmentRecord)orderedEnrollmentList.get(index);
					if (enrollee.getUser().getUserUid().equals(getStudentUid())) {
						currentStudent = enrollee;
						if (index-1 >= 0) {
							previousStudent = (EnrollmentRecord) orderedEnrollmentList.get(index-1);
						}
						if (index+1 < orderedEnrollmentList.size()) {
							nextStudent = (EnrollmentRecord) orderedEnrollmentList.get(index+1);
						}
						break;
					}
					index++;
				}
			}

			setSortColumn(sortByCol);
			setSortAscending(sortAsc);

		}
	}

	// Navigation
	public EnrollmentRecord getPreviousStudent() {
		return previousStudent;
	}
	public EnrollmentRecord getNextStudent() {
		return nextStudent;
	}
	
	public boolean isFirst() {
		return previousStudent == null;
	}
	public boolean isLast() {
		return nextStudent == null;
	}
	
	public EnrollmentRecord getCurrentStudent() {
		return currentStudent;
	}

	/**
	 * @return text for "Return to" button
	 */
	public String getReturnToPageButtonName() {
		String pageTitle;
		if (ASSIGN_DETAILS_PAGE.equals(returnToPage))
			pageTitle = getLocalizedString("assignment_details_page_title");
		else
			pageTitle = getLocalizedString("roster_page_title");

		return getLocalizedString("inst_view_return_to", new String[] {pageTitle});
	}
	
	/**
	 * 
	 * @return page title of originating page
	 */
	public String getReturnToPageName() {
		if (returnToPage.equals(ASSIGN_DETAILS_PAGE))
			return getLocalizedString("assignment_details_page_title");
		else
			return getLocalizedString("roster_page_title");
	}
	
	/**
	 * 
	 * @return comma-separated string of user's section/group memberships
	 */
	public String getStudentSections() {
		return studentSections;
	}
	
    /**
     * @return studentEmailAddress
     */
    public String getStudentEmailAddress() {
        return studentEmailAddress;
    }

	/**
	 * Action listener to view a different student
	 */
	public void processStudentUidChange(ActionEvent event) {
		Map params = FacesUtil.getEventParameterMap(event);
		if (logger.isDebugEnabled()) 
			logger.debug("processStudentUidChange params=" + params + ", current studentUid=" + getStudentUid());
		// run the updates before changing the student id
		processUpdateScoresForPreNextStudent();
		String idParam = (String)params.get("studentUid");
		if (idParam != null) {
			setStudentUid(idParam);
		}
	}
	
	public void processUpdateScoresForPreNextStudent() {
		try {
			saveScoresWithoutConfirmation();
		} catch (StaleObjectModificationException e) {
			FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure"));
		}
	}
	
	/**
{'fraction_non_alphanumeric': 0.11623827320570514, 'fraction_numerical': 0.004652581801540691, 'mean_word_length': 4.830146731880836, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1223438', 'n_tokens_mistral': 4211, 'n_tokens_neox': 3696, 'n_words': 875}