<%page expression_filter="h"/>
<%inherit file="main.html" />
<%def name="online_help_token()"><% return "learnerdashboard" %></%def>
<%namespace name='static' file='static_content.html'/>
<%!
import pytz
from courseware.context_processor import user_timezone_locale_prefs
from datetime import datetime, timedelta
from django.utils import timezone
from django.utils.translation import ugettext as _
from django.template import RequestContext
from third_party_auth import pipeline
from django.core.urlresolvers import reverse
from util.date_utils import strftime_localized
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.theming import helpers as theming_helpers
from openedx.core.djangolib.js_utils import dump_js_escaped_json, js_escaped_string
from openedx.core.djangolib.markup import HTML, Text

from entitlements.models import CourseEntitlement
from student.models import CourseEnrollment
%>

<%
  cert_name_short = settings.CERT_NAME_SHORT
  cert_name_long = settings.CERT_NAME_LONG
%>


<%block name="pagetitle">${_("Dashboard")}</%block>
<%block name="bodyclass">view-dashboard is-authenticated</%block>

<%block name="header_extras">
% for template_name in ["donation"]:
<script type="text/template" id="${template_name}-tpl">
  <%static:include path="dashboard/${template_name}.underscore" />
</script>
% endfor
</%block>

<%block name="js_extra">
  <script src="${static.url('js/commerce/credit.js')}"></script>
  <%static:js group='dashboard'/>
  <script type="text/javascript">
    $(document).ready(function() {
      edx.dashboard.legacy.init({
        dashboard: "${reverse('dashboard') | n, js_escaped_string}",
        signInUser: "${reverse('signin_user') | n, js_escaped_string}",
        changeEmailSettings: "${reverse('change_email_settings') | n, js_escaped_string}"
      });
    });
  </script>
  <%static:require_module module_name="js/learner_dashboard/unenrollment_factory" class_name="UnenrollmentFactory">
    UnenrollmentFactory({
      urls: {
        dashboard: "${reverse('dashboard') | n, js_escaped_string}",
        signInUser: "${reverse('signin_user') | n, js_escaped_string}",
        changeEmailSettings: "${reverse('change_email_settings') | n, js_escaped_string}",
        browseCourses: "${marketing_link('COURSES') | n, js_escaped_string}"
      },
      isEdx: true
    });
  </%static:require_module>
  % if settings.FEATURES.get('ENABLE_DASHBOARD_SEARCH'):
    <%static:require_module module_name="course_search/js/dashboard_search_factory" class_name="DashboardSearchFactory">
        DashboardSearchFactory();
    </%static:require_module>
  % endif
  % if redirect_message:
    <%static:require_module module_name="js/views/message_banner" class_name="MessageBannerView">
        var banner = new MessageBannerView({urgency: 'low', type: 'warning'});
        $('#content').prepend(banner.$el);
        banner.showMessage(${redirect_message | n, dump_js_escaped_json})
    </%static:require_module>
  % endif
</%block>

<div class="dashboard-notifications" tabindex="-1">

    %if banner_account_activation_message:
        <div class="dashboard-banner">
            ${banner_account_activation_message | n, decode.utf8}
        </div>
    %endif

    %if enrollment_message:
        <section class="dashboard-banner">
            ${enrollment_message | n, decode.utf8}
        </section>
    %endif

    %if enterprise_message:
        <div class="dashboard-banner">
            ${ enterprise_message | n, decode.utf8 }
        </div>
    %endif

    %if account_activation_messages:
      <div class="activation-message-container">
        % for account_activation_message in account_activation_messages:
          <div class="account-activation ${account_activation_message.tags}" role="alert" aria-label="Account Activation Message" tabindex="-1">
            <div class="message-copy" >
              ${ account_activation_message | n, decode.utf8 }
            </div>
          </div>
        % endfor
      </div>
    %endif

</div>

<section class="dashboard" id="dashboard-main">
<main class="main-container" id="main" aria-label="Content" tabindex="-1">
  <section class="my-courses" id="my-courses">
    <header class="wrapper-header-courses">
      <h2 class="header-courses">${_("My Courses")}</h2>
    </header>
    % if len(course_entitlements + course_enrollments) > 0:
        <ul class="listing-courses">
        <% share_settings = getattr(settings, 'SOCIAL_SHARING_SETTINGS', {}) %>
        % for dashboard_index, enrollment in enumerate(course_entitlements + course_enrollments):
          <%
            # Check if the course run is an entitlement and if it has an associated session
            entitlement = enrollment if isinstance(enrollment, CourseEntitlement) else None
            entitlement_session = entitlement.enrollment_course_run if entitlement else None
            entitlement_days_until_expiration = entitlement.get_days_until_expiration() if entitlement else None
            entitlement_expiration = datetime.now(tz=pytz.UTC) + timedelta(days=entitlement_days_until_expiration) if (entitlement and entitlement_days_until_expiration < settings.ENTITLEMENT_EXPIRED_ALERT_PERIOD) else None
            entitlement_expiration_date = strftime_localized(entitlement_expiration, 'SHORT_DATE') if entitlement and entitlement_expiration else None
            entitlement_expired_at = strftime_localized(entitlement.expired_at_datetime, 'SHORT_DATE') if entitlement and entitlement.expired_at_datetime else None

            is_fulfilled_entitlement = True if entitlement and entitlement_session else False
            is_unfulfilled_entitlement = True if entitlement and not entitlement_session else False

            entitlement_available_sessions = []
            if entitlement:
              # Grab the available, enrollable sessions for a given entitlement and scrape them for relevant attributes
              entitlement_available_sessions = [{
                'session_id': course['key'],
                'enrollment_end': course['enrollment_end'],
                'pacing_type': course['pacing_type'],
                'advertised_start': CourseOverview.get_from_id(CourseKey.from_string(course['key'])).advertised_start,
                'start': CourseOverview.get_from_id(CourseKey.from_string(course['key'])).start,
                'end': CourseOverview.get_from_id(CourseKey.from_string(course['key'])).end,
                } for course in course_entitlement_available_sessions[str(entitlement.uuid)]]
              if is_fulfilled_entitlement:
                # If the user has a fulfilled entitlement, pass through the entitlements CourseEnrollment object
                enrollment = entitlement_session
              else:
                # If the user has an unfulfilled entitlement, pass through a bare CourseEnrollment object built off of the next available session
                upcoming_sessions = course_entitlement_available_sessions[str(entitlement.uuid)]
                next_session = upcoming_sessions[0] if upcoming_sessions else None
                if not next_session:
                    continue
                enrollment = CourseEnrollment(user=user, course_id=next_session['key'], mode=next_session['type'])

            session_id = enrollment.course_id
            show_courseware_link = (session_id in show_courseware_links_for)
            cert_status = cert_statuses.get(session_id)
            can_unenroll = (not cert_status) or cert_status.get('can_unenroll') if not unfulfilled_entitlement else False
            credit_status = credit_statuses.get(session_id)
            show_email_settings = (session_id in show_email_settings_for)
            course_mode_info = all_course_modes.get(session_id)
            is_paid_course = True if entitlement else (session_id in enrolled_courses_either_paid)
            is_course_blocked = (session_id in block_courses)
            course_verification_status = verification_status_by_course.get(session_id, {})
            course_requirements = courses_requirements_not_met.get(session_id)
            related_programs = inverted_programs.get(unicode(session_id))
            show_consent_link = (session_id in consent_required_courses)
            course_overview = enrollment.course_overview
          %>
          <%include file='dashboard/_dashboard_course_listing.html' args='course_overview=course_overview, course_card_index=dashboard_index, enrollment=enrollment, is_unfulfilled_entitlement=is_unfulfilled_entitlement, is_fulfilled_entitlement=is_fulfilled_entitlement, entitlement=entitlement, entitlement_session=entitlement_session, entitlement_available_sessions=entitlement_available_sessions, entitlement_expiration_date=entitlement_expiration_date, entitlement_expired_at=entitlement_expired_at, show_courseware_link=show_courseware_link, cert_status=cert_status, can_unenroll=can_unenroll, credit_status=credit_status, show_email_settings=show_email_settings, course_mode_info=course_mode_info, is_paid_course=is_paid_course, is_course_blocked=is_course_blocked, verification_status=course_verification_status, course_requirements=course_requirements, dashboard_index=dashboard_index, share_settings=share_settings, user=user, related_programs=related_programs, display_course_modes_on_dashboard=display_course_modes_on_dashboard, show_consent_link=show_consent_link, enterprise_customer_name=enterprise_customer_name' />
        % endfor
        </ul>
    % else:
      <section class="empty-dashboard-message">
        <p>${_("You are not enrolled in any courses yet.")}</p>

        % if settings.FEATURES.get('COURSES_ARE_BROWSABLE'):
          <a class="btn btn-primary" href="${marketing_link('COURSES')}">
            ${_("Explore courses")}
          </a>
        %endif
      </section>
    % endif

    % if staff_access and len(errored_courses) > 0:
      <div id="course-errors">
        <h2>${_("Course-loading errors")}</h2>

      % for course_dir, errors in errored_courses.items():
         <h3>${course_dir}</h3>
             <ul>
           % for (msg, err) in errors:
               <li>${msg}
                 <ul><li><pre>${err}</pre></li></ul>
               </li>
           % endfor
             </ul>
      % endfor
      </div>
    % endif
  </section>
</main>
<div class="side-container">
  %if sidebar_account_activation_message:
    <div class="sidebar-notification">
      ${sidebar_account_activation_message | n, decode.utf8}
    </div>
  %endif

  % if settings.FEATURES.get('ENABLE_DASHBOARD_SEARCH'):
    <div id="dashboard-search-bar" class="search-bar dashboard-search-bar" role="search" aria-label="Dashboard">
      <form class="search-form">
        <label for="dashboard-search-input">${_('Search Your Courses')}</label>
        <div class="search-field-wrapper">
          <input id="dashboard-search-input" type="text" class="search-field"/>
          <button type="submit" class="search-button" title="${_('Search')}">
            <span class="icon fa fa-search" aria-hidden="true"></span>
          </button>
          <button type="button" class="cancel-button" title="${_('Clear search')}">
            <span class="icon fa fa-remove" aria-hidden="true"></span>
          </button>
        </div>
      </form>
    </div>
    <section id="dashboard-search-results" class="search-results dashboard-search-results"></section>
  % endif

  % if settings.FEATURES.get('COURSES_ARE_BROWSABLE'):
      <div class="wrapper-find-courses">
          <div class="course-advertise">
              <div class="advertise-message">
                  ${_("Browse recently launched courses and see what's new in your favorite subjects.")}
              </div>
              <div class="ad-link">
                  <a class="btn-neutral" href="${marketing_link('COURSES')}">
                      <span class="icon fa fa-search" aria-hidden="true"></span>
                      ${_("Explore New Courses")}
                  </a>
              </div>
          </div>
      </div>
  % endif

  % if display_sidebar_on_dashboard:
    <section class="profile-sidebar" id="profile-sidebar" role="region" aria-label="Account Status Info">
      <header class="profile">
        <h2 class="account-status-title sr">${_("Account Status Info")}: </h2>
      </header>
      <section class="user-info">
        <ul>

          % if len(order_history_list):
          <li class="order-history">
            <span class="title">${_("Order History")}</span>
            % for order_history_item in order_history_list:
              <span><a href="${order_history_item['receipt_url']}" target="_blank" class="edit-name">${order_history_item['order_date']}</a></span>
            % endfor
          </li>
          % endif

          <%include file="${theming_helpers.get_template_path('dashboard/_dashboard_status_verification.html')}" />

        </ul>
      </section>
    </section>
  % endif
</div>
</section>

<section id="email-settings-modal" class="modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="email-settings-title">
    <button class="close-modal">
      <span class="icon fa fa-remove" aria-hidden="true"></span>
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_("Close")}
      </span>
    </button>

    <header>
      <h2 id="email-settings-title">
        ${Text(_("Email Settings for {course_number}")).format(course_number=HTML('<span id="email_settings_course_number"></span>'))}
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("window open")}
        </span>
      </h2>
      <hr/>
    </header>

    <form id="email_settings_form" method="post">
      <input name="course_id" id="email_settings_course_id" type="hidden" />
      <label>${_("Receive course emails")} <input type="checkbox" id="receive_emails" name="receive_emails" /></label>
      <div class="submit">
        <input type="submit" id="submit" value="${_("Save Settings")}" />
      </div>
    </form>
  </div>
</section>

<section id="unenroll-modal" class="modal unenroll-modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="unenrollment-modal-title">
    <button class="close-modal">
      <span class="icon fa fa-remove" aria-hidden="true"></span>
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_("Close")}
      </span>
    </button>

    <header class="unenroll-header">
      <h2 id="unenrollment-modal-title">
        <span id='track-info'></span>
        <span id='refund-info'></span>
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("window open")}
        </span>
      </h2>
      <hr/>
    </header>
    <div id="unenroll_error" class="modal-form-error"></div>
    <form id="unenroll_form" method="post" data-remote="true" action="${reverse('change_enrollment')}">
      <input name="course_id" id="unenroll_course_id" type="hidden" />
      <input name="enrollment_action" type="hidden" value="unenroll" />
      <div class="submit">
        <input name="submit" type="submit" value="${_("Unenroll")}" />
      </div>
    </form>
    <%include file='dashboard/_reason_survey.html' />
  </div>
</section>
