import { LessonResource, ContentNodeResource, LearnerGroupResource } from 'kolibri.resources';
import find from 'lodash/find';
import { showExerciseDetailView } from './reports.js';
import LessonReportResource from '../../apiResources/lessonReport';
import UserReportResource from '../../apiResources/userReport';
import { CollectionTypes, LessonsPageNames } from '../../lessonsConstants';
import { getChannelObject } from 'kolibri.coreVue.vuex.getters';
import { handleApiError } from 'kolibri.coreVue.vuex.actions';

/* Refreshes the Lesson Report (resource vs. fraction of learners-who-completed-it)
 * data on the Lesson Summary Page.
 */
export function refreshLessonReport(store, lessonId) {
  LessonReportResource.getModel(lessonId)
    .fetch({}, true)
    .then(lessonReport => {
      store.dispatch('SET_LESSON_REPORT', lessonReport);
    });
}

/*
 * Shows the Lesson Resource Progress Report (all assigned learners vs. progress on resource).
 */
export function showLessonResourceUserSummaryPage(store, classId, lessonId, contentId) {
  store.dispatch('CORE_SET_PAGE_LOADING', true);

  const loadRequirements = [
    // Used to get Lesson.learner_ids
    LessonResource.getModel(lessonId).fetch(),
    // Get ContentNode to get the resource kind, title, etc., and channel ID for Report API
    ContentNodeResource.getModel(contentId).fetch(),
    // Get group names
    LearnerGroupResource.getCollection({ parent: classId }).fetch(),
  ];

  return Promise.all(loadRequirements)
    .then(([lesson, contentNode, learnerGroups]) => {
      const channelObject = getChannelObject(store.state, contentNode.channel_id);
      const getLearnerGroup = userId => find(learnerGroups, g => g.user_ids.includes(userId)) || {};

      // IDEA filter by ids?
      return UserReportResource.getCollection({
        channel_id: contentNode.channel_id,
        collection_id: classId,
        collection_kind: CollectionTypes.CLASSROOM,
        content_node_id: contentNode.pk,
      })
        .fetch()
        ._promise.then(userReports => {
          const getUserReport = userId => find(userReports, { pk: userId }) || {};
          const userData = lesson.learner_ids.map(learnerId => {
            const { full_name, last_active, progress } = getUserReport(learnerId);
            return {
              id: learnerId,
              name: full_name,
              lastActive: last_active,
              groupName: getLearnerGroup(learnerId).name,
              progress: progress[0].total_progress,
            };
          });

          store.dispatch('SET_PAGE_STATE', {
            channelTitle: channelObject.title,
            resourceTitle: contentNode.title,
            resourceKind: contentNode.kind,
            userData,
          });
          store.dispatch('SET_TOOLBAR_ROUTE', { name: LessonsPageNames.SUMMARY });
          store.dispatch('SET_PAGE_NAME', LessonsPageNames.RESOURCE_USER_SUMMARY);
          store.dispatch('CORE_SET_PAGE_LOADING', false);
        });
    })
    .catch(error => {
      store.dispatch('CORE_SET_PAGE_LOADING', false);
      return handleApiError(store, error);
    });
}

/* eslint-disable no-unused-vars */
export function showLessonResourceUserReportPage(
  store,
  classId,
  lessonId,
  contentId,
  userId,
  questionNumber,
  interactionNumber
) {
  store.dispatch('CORE_SET_PAGE_LOADING', true);
  store.dispatch('SET_PAGE_NAME', LessonsPageNames.RESOURCE_USER_REPORT);
  store.dispatch('SET_PAGE_STATE', {
    toolbarRoute: { name: LessonsPageNames.RESOURCE_USER_SUMMARY },
  });
  // TODO set title
  ContentNodeResource.getModel(contentId)
    .fetch()
    .then(contentNode => {
      showExerciseDetailView(
        store,
        classId,
        userId,
        contentNode.channel_id,
        contentId,
        questionNumber,
        interactionNumber
      );
    });
}

@@ -1,16 +1,48 @@
+import find from 'lodash/find';%0A
 import %7B LessonR
@@ -124,95 +124,8 @@
 s';%0A
-import find from 'lodash/find';%0Aimport %7B showExerciseDetailView %7D from './reports.js';%0A
 impo
@@ -455,16 +455,68 @@
 ctions';
+%0Aimport %7B showExerciseDetailView %7D from './reports';
 %0A%0A/* Ref
@@ -2740,24 +2740,87 @@
         %7D);%0A
+          store.dispatch('CORE_SET_TITLE', contentNode.title);%0A
           st
@@ -2886,24 +2886,24 @@
 SUMMARY %7D);%0A
-
           st
@@ -3186,38 +3186,50 @@
 %0A%0A/*
- eslint-disable no-unused-vars
+%0A * Shows the attempt log for an Exercise%0A
  */%0A
@@ -3613,28 +3613,8 @@
 %7D);%0A
-  // TODO set title%0A
   Co
@@ -3674,16 +3674,23 @@
   .then(
+%0A      
 contentN
@@ -3694,24 +3694,157 @@
 ntNode =%3E %7B%0A
+        store.dispatch('CORE_SET_TITLE', contentNode.title);%0A        // NOTE: returning the result causes problems for some reason%0A  
       showEx
@@ -3869,23 +3869,27 @@
         
+ 
+ 
 store,%0A
+  
         
@@ -3905,24 +3905,26 @@
         
+ 
+ 
 userId,%0A
         
@@ -3911,24 +3911,26 @@
     userId,%0A
+  
         cont
@@ -3941,32 +3941,34 @@
 ode.channel_id,%0A
+  
         contentI
@@ -3978,16 +3978,18 @@
         
+  
 question
@@ -3996,16 +3996,18 @@
 Number,%0A
+  
         
@@ -4030,21 +4030,157 @@
 r%0A      
+ 
+ 
 );%0A    
-%7D
+  %7D,%0A      error =%3E %7B%0A        store.dispatch('CORE_SET_PAGE_LOADING', false);%0A        return handleApiError(store, error);%0A      %7D%0A    
 );%0A%7D%0A

Set titles for lesson reports pages