__author__ = 'ehiller@css.edu'


# Module to support custom teacher views in CourseBuilder dashboard
# Views include:
#       Section Roster - list of students in section
#       Sections - list of s
ections for current user
#       Student Dashboard - view of a single student's performance in the course
#       Teacher Workspace - teacher registration and list of all registered teachers

import jinja2
import os

im
port appengine_config

from common import tags
from common import crypto

from models import custom_modules
from models import roles
from models import transforms
from models.models import Student

#since we are extending the dashboard, probably want to include dashboard stuff
from modules.dashboard import dashboard
from modules.dashboard import tabs

#import our own modules
import teacher_entity
import teacher_rest_handlers
import teacher_parsers

#Setup paths and directories for templates and resources
RESOURCES_PATH = '/modules/teacher_dashboard/resources'

TEMPLATES_DIR = os.path.join(
    appengine_config.BUNDLE_ROOT, 'modules', 'teacher_dashboard', 'templates')

#setup permissions that will be registered with the dashboard
ACCESS_ASSETS_PERMISSION = 'can_access_assets'
ACCESS_ASSETS_PERMISSION_DESCRIPTION = 'Can access the Assets Dashboard'

ACCESS_SETTINGS_PERMISSION = 'can_access_settings'
ACCESS_SETTINGS_PERMISSION_DESCRIPTION = 'Can access the Settings Dashboard'

ACCESS_ROLES_PERMISSION = 'can_access_roles'
ACCESS_ROLES_PERMISSION_DESCRIPTION = 'Can access the Roles Dashboard'

ACCESS_ANALYTICS_PERMISSION = 'can_access_analytics'
ACCESS_ANALYTICS_PERMISSION_DESCRIPTION = 'Can access the Analytics Dashboard'

ACCESS_SEARCH_PERMISSION = 'can_access_search'
ACCESS_SEARCH_PERMISSION_DESCRIPTION = 'Can access the Search Dashboard'

ACCESS_PEERREVIEW_PERMISSION = 'can_access_peer_review'
ACCESS_PEERREVIEW_PERMISSION_DESCRIPTION = 'Can access the Peer Review Dashboard'

ACCESS_SKILLMAP_PERMISSION = 'can_access_skill_map'
ACCESS_SKILLMAP_PERMISSION_DESCRIPTION = 'Can access the Skill Map Dashboard'

ACCESS_TEACHER_DASHBOARD_PERMISSION = 'can_access_teacher_dashboard'
ACCESS_TEACHER_DASHBOARD_PERMISSION_DESCRIPTION = 'Can access the Teacher Dashboard'

#setup custom module for, needs to be referenced later
custom_module = None


class TeacherHandler(dashboard.DashboardHandler):
    """Handler for everything under the Teacher tab in the CourseBuilder dashboard.

    Note:
        Inherits from the DashboardHandler, makes use of many of those functions to
        integrate with existing dashboard.

    Attributes:
        ACTION (str): Value used to handler navigation in the dashboard, top level label.
        DEFAULT_TAB (str): Default sub-navigation value.
        URL (str): Path to module from working directory.
        XSRF_TOKEN_NAME (str): Token used for xsrf security functions.

    """

    ACTION = 'teacher_dashboard'
    DEFAULT_TAB = 'sections'

    URL = '/modules/teacher_dashboard'

    XSRF_TOKEN_NAME = ''

    @classmethod
    def register_tabs(cls):
        """Handles registering all sub-navigation tabs"""

        def register_tab(key, label, handler, href=None):
            """Registers tab using the tab registry"""
            if href:
                target = '_blank'
            else:
                href = 'dashboard?action=teacher_dashboard&tab=%s' % key
                target = None

            tabs.Registry.register(
                cls.ACTION, key, label, contents=handler, href=href, target=target
            )

        register_tab('sections', 'Sections', TeacherHandler)
        register_tab('student_detail', 'Student Dashboard', TeacherHandler)
        register_tab('teacher_reg', 'Teacher Workspace', TeacherHandler)

    def get_teacher_dashboard(self):
        """Process navigation requests sent to teacher handler. Routers to appropriate function."""

        in_tab = self.request.get('tab') or self.DEFAULT_TAB
        tab_action = self.request.get('tab_action') or None #defined a secondary tab property so I can go load a
                                                            # separate view in the same tab

        if in_tab == 'sections':
            if tab_action == 'roster':
                return self.get_roster()
            else:
                return self.get_sections()
        elif in_tab == 'teacher_reg':
            return self.get_teacher_reg()
        elif in_tab == 'student_detail':
            return self.get_student_dashboard()

    def get_sections(self):
        """Renders Sections view. Javascript handles getting course sections and building the view"""
        template_values = {}
        template_values['namespace'] = self.get_course()._namespace.replace('ns_', '')

        main_content = self.get_template(
            'teacher_sections.html', [TEMPLATES_DIR]).render(template_values)

        self.render_page({
            'page_title': self.format_title('Sections'),
            'main_content': jinja2.utils.Markup(main_content)})

    def get_student_dashboard(self):
        """Renders Student Dashboard view.

           Also gets ALL students in ALL course sections for the registered user to
           build a jQuery autocomplete dropdown on the view.
        """

        student_email = self.request.get('student') or None #email will be in the request if opened from student list
                                                            # view, otherwise it will be None

        #need to go through every course section for the current user and get all unique students
        students = []
        course_sections = teacher_entity.CourseSectionEntity.get_course_sections_for_user()
        if course_sections and len(course_sections) > 0:
            for course_section in course_sections.values():
                if course_section.students and len(course_section.students) > 0:
                    for student_in_section in course_section.students.values():
                        if not any(x['user_id'] == student_in_section['user_id'] for x in students):
                            students.append(student_in_section)

        #check to see if we have a student and if we need to get detailed progress
        student = None
        if student_email:
            student = Student.get_by_email(student_email)

        if (student):
            course = self.get_course()
            units = teacher_parsers.StudentProgressTracker.get_detailed_progress(student, course)
            scores = teacher_parsers.ActivityScoreParser.get_activity_scores([student.user_id], course)
        else:
            units = None
            scores = None

        #render the template for the student dashboard view
        main_content = self.get_template(
            'student_detailed_progress.html', [TEMPLATES_DIR]).render(
                {
                    'units': units, #unit completion
                    'student': student, #course defined student object, need email and name
                    'students': students, #list of students, names and emails, from a course section student list
                    'scores': scores
                })

        #call DashboardHandler function to render the page
        self.render_page({
            'page_title': self.format_title('Student Dashboard'),
            'main_content': jinja2.utils.Markup(main_content)
        })


    def get_roster(self):
        """Renders the Roster view. Displays all students in a single course section

           Also allows user to add students to a course section
        """

        template_values = {}
        template_values['add_student_xsrf_token'] = crypto.XsrfTokenManager.create_xsrf_token(
            teacher_rest_handlers.CourseSectionRestHandler.XSRF_TOKEN)

        #need list of units and lessons for select elements that determine which progress value to display
        #need a list of units, need the titles, unit ids, types
        units = self.get_course().get_units()
        units_filtered = filter(lambda x: x.type == 'U', units) #filter out assessments
        template_values['units'] = units_filtered

        #need to get lessons, but only for units that aren't assessments
        lesson