<commit_before>/**
 * Created by AMOS on 10/7/16.
 */


//TODO: Add various imports for challenge(s)
import * as mcq from './mcq/mcq.js';
import * as survey from './survey/survey.js';
import * as team from './teamActivity/teamactivity.js';

const noop = () => undefined;

//TODO: Add config for routing to various challenges
export function configRoute($routeProvider, routes){
    $routeProvider
        .when(routes.viewMcq, {
            template: mcq.newMcqTmpl,
            controller: mcq.newMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: createMCQInitialData
            }
        })

        .when(routes.editMcq, {
            template: mcq.editMcqTmpl,
            controller: mcq.editMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: editMCQInitialData
            }

        })

        .when(routes.viewSurvey, {
            template: survey.showSurveyTmpl,
            controller: surveyFormEvent,
            controllerAs: 'ctrl',
            resolve: {
                initialData: getTaskSurveyValues
            }
        })

        .when(routes.startMcq, {
            template: mcq.starMcqTmpl,
            controller: mcq.startMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: startMCQInitialData
            }
        })

        .when(routes.createTeamActivity, {
            template: team.teamActivityCreateTmpl,
            controller: team.createTeamActivityController,
            controllerAs: 'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewIRAT,{
            template: team.teamIRATTmpl,
            controller: team.startIRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewTRAT,{
            template: team.teamTRATTmpl,
            controller: team.startTRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }

        });

}
configRoute.$inject = ['$routeProvider', 'routes'];


function editMCQInitialData($q, eventService, clmDataStore){
  var data = eventService.get();
  console.log(data);
  return clmDataStore.events.getTaskAnswers(data.event.$id, data.task.$id).then(
      function(result){
        return {
          data: data,
          savedAnswers: result
        }
      }, function(error){
        console.log(error);
      }
  );
}
editMCQInitialData.$inject = [
    '$q',
    'eventService',
    'clmDataStore'
];

// Initial data for starting an MCQ
//todo: tidy up the codes; should be using promises to access some objects as well as validation
function startMCQInitialData($q, spfAuthData, eventService, clmDataStore){
    //promise object
   // var currentUser = spfAuthData.user().catch(noop);

    var data =  eventService.get();

    console.log("the data is here...,", data);
    //console.log("current user now is.", currentUser);

    return $q.all ({
       currentUser: spfAuthData.user(),
        answers: clmDataStore.events.getTaskAnswers(data.eventId, data.taskId),
        getProgress: clmDataStore.events.getProgress(data.eventId)
    }).then (function (result){
        return {
            data: data,
            correctAnswers: result.answers,
            currentUser: result.currentUser,
            progress: result.getProgress
        }
    });

    // return clmDataStore.events.getTaskAnswers(data.eventId, data.taskId).then(
    //       function(result){
    //         return {
    //           data: data,
    //           correctAnswers: result,
    //             currentUser: currentUser
    //         }
    //       }, function(error){
    //         console.log(error);
    //       }
    //   );
}
startMCQInitialData.$inject = [
    '$q',
    'spfAuthData',
    'eventService',
    'clmDataStore'
]

// Initial data for creating MCQ
function createMCQInitialData($q, eventService){
  var data =  eventService.get();
  console.log("data initialised are............................",data);
  return data;
}
createMCQInitialData.$inject = [
  '$q',
  'eventService'
]

//TODO: Generic save function
export function challengeServiceFactory
  ($q, $route, spfAuthData, clmDataStore, spfFirebase, $log, spfAlert, $location, urlFor){
  return {
    save : function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS!! ', copy);
      self.creatingTask = true;
      if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;

        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers);
        ref.then(function() {
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to created new task');
        }).finally(function() {
            self.creatingTask = false;
        });

      } else if(taskType === 'teamActivity'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;
        if(copy.link == ""){
          delete copy.link;
        }
        console.log(copy);
        // Create reccord in eventTeams
        // Add IRAT
        clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers)
          .then(function(ref){
            //add Team formation task
            var previousTaskId = ref.key();
            console.log('IRAT key is :', previousTaskId);
            clmDataStore.events.addTeamFormation(event.$id, {
                taskFrom: previousTaskId,
                title: copy.title,
                description: "Click Below To Join Team",
                formationPattern: true,
                closedAt : {'.sv': 'timestamp'},
                showProgress: copy.showProgress,
                archived: false,
                teamFormationMethod: copy.teamFormationMethod
            }, copy.priority).then(function(teamRef){
              //create teams here
              var taskId = teamRef.key()
              console.log('taskId: ', taskId);
              console.log(event.teams);
              spfFirebase.set(['classMentors/eventTeams', event.$id],taskId)
              .then(function(){
                // For each team create a reccord in Firebase
                for(var i = 0; i < event.teams.length; i ++){
                    var team = event.teams[i];
                    // console.log('Team here is: ', team);
                    spfFirebase.push(['classMentors/eventTeams/', event.$id,taskId],team)
                    .then(function(ref){
                        console.log('Team ', i , 'pushed with key: ', ref.key());
                    });
                }
              });
                clmDataStore.events.addTrat(event.$id,{
                    taskFrom: taskId,
                    title: copy.title,
                    description: "Click Below to Start TRAT",
                    startTRAT: true,
                    closedAt : {'.sv': 'timestamp'},
                    showProgress: copy.showProgress,
                    archived: false,
                    teamFormationMethod: copy.teamFormationMethod,
                    mcqQuestions: copy.mcqQuestions
                },copy.priority).then(function(ref){<commit_msg>trat task creation<commit_after>/**
 * Created by AMOS on 10/7/16.
 */


//TODO: Add various imports for challenge(s)
import * as mcq from './mcq/mcq.js';
import * as survey from './survey/survey.js';
import * as team from './teamActivity/teamactivity.js';

const noop = () => undefined;

//TODO: Add config for routing to various challenges
export function configRoute($routeProvider, routes){
    $routeProvider
        .when(routes.viewMcq, {
            template: mcq.newMcqTmpl,
            controller: mcq.newMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: createMCQInitialData
            }
        })

        .when(routes.editMcq, {
            template: mcq.editMcqTmpl,
            controller: mcq.editMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: editMCQInitialData
            }

        })

        .when(routes.viewSurvey, {
            template: survey.showSurveyTmpl,
            controller: surveyFormEvent,
            controllerAs: 'ctrl',
            resolve: {
                initialData: getTaskSurveyValues
            }
        })

        .when(routes.startMcq, {
            template: mcq.starMcqTmpl,
            controller: mcq.startMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: startMCQInitialData
            }
        })

        .when(routes.createTeamActivity, {
            template: team.teamActivityCreateTmpl,
            controller: team.createTeamActivityController,
            controllerAs: 'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewIRAT,{
            template: team.teamIRATTmpl,
            controller: team.startIRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewTRAT,{
            template: team.teamTRATTmpl,
            controller: team.startTRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }

        });

}
configRoute.$inject = ['$routeProvider', 'routes'];


function editMCQInitialData($q, eventService, clmDataStore){
  var data = eventService.get();
  console.log(data);
  return clmDataStore.events.getTaskAnswers(data.event.$id, data.task.$id).then(
      function(result){
        return {
          data: data,
          savedAnswers: result
        }
      }, function(error){
        console.log(error);
      }
  );
}
editMCQInitialData.$inject = [
    '$q',
    'eventService',
    'clmDataStore'
];

// Initial data for starting an MCQ
//todo: tidy up the codes; should be using promises to access some objects as well as validation
function startMCQInitialData($q, spfAuthData, eventService, clmDataStore){
    //promise object
   // var currentUser = spfAuthData.user().catch(noop);

    var data =  eventService.get();
    console.log("my data is:", data);
    return $q.all ({
       currentUser: spfAuthData.user(),
        answers: clmDataStore.events.getTaskAnswers(data.eventId, data.task.taskFromIrat),
        getProgress: clmDataStore.events.getProgress(data.eventId)
    }).then (function (result){
        console.log("result issss:", result);
        return {
            data: data,
            correctAnswers: result.answers,
            currentUser: result.currentUser,
            progress: result.getProgress
        }
    });

    // return clmDataStore.events.getTaskAnswers(data.eventId, data.taskId).then(
    //       function(result){
    //         return {
    //           data: data,
    //           correctAnswers: result,
    //             currentUser: currentUser
    //         }
    //       }, function(error){
    //         console.log(error);
    //       }
    //   );
}
startMCQInitialData.$inject = [
    '$q',
    'spfAuthData',
    'eventService',
    'clmDataStore'
]

// Initial data for creating MCQ
function createMCQInitialData($q, eventService){
  var data =  eventService.get();
  console.log("data initialised are............................",data);
  return data;
}
createMCQInitialData.$inject = [
  '$q',
  'eventService'
]

//TODO: Generic save function
export function challengeServiceFactory
  ($q, $route, spfAuthData, clmDataStore, spfFirebase, $log, spfAlert, $location, urlFor){
  return {
    save : function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS!! ', copy);
      self.creatingTask = true;
      if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;

        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers);
        ref.then(function() {
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to created new task');
        }).finally(function() {
            self.creatingTask = false;
        });

      } else if(taskType === 'teamActivity'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;
        if(copy.link == ""){
          delete copy.link;
        }
        console.log(copy);
        // Create reccord in eventTeams
        // Add IRAT
        clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers)
          .then(function(ref){
            //add Team formation task
            var previousTaskId = ref.key();
            console.log('IRAT key is :', previousTaskId);
            clmDataStore.events.addTeamFormation(event.$id, {
                taskFrom: previousTaskId,
                title: copy.title,
                description: "Click Below To Join Team",
                formationPattern: true,
                closedAt : {'.sv': 'timestamp'},
                showProgress: copy.showProgress,
                archived: false,
                teamFormationMethod: copy.teamFormationMethod
            }, copy.priority).then(function(teamRef){
              //create teams here
              var taskId = teamRef.key()
              console.log('taskId: ', taskId);
              console.log(event.teams);
              spfFirebase.set(['classMentors/eventTeams', event.$id],taskId)
              .then(function(){
                // For each team create a reccord in Firebase
                for(var i = 0; i < event.teams.length; i ++){
                    var team = event.teams[i];
                    // console.log('Team here is: ', team);
                    spfFirebase.push(['classMentors/eventTeams/', event.$id,taskId],team)
                    .then(function(ref){
                        console.log('Team ', i , 'pushed with key: ', ref.key());
                    });
                }
              });
                clmDataStore.events.addTrat(event.$id,{
                    taskFrom: taskId,
                    taskFromIrat: previousTaskId,
                    title: copy.title,
                    description: "Click Below to Start TRAT",
                    startTRAT: true,
                    closedAt : {'.sv': 'timestamp'},
                    showProgress: copy.showProgress,
                    archived: false,
                    teamFormationMethod: copy.teamFormationMethod,
                    mcqQuestions: copy.mcqQuestions
                },copy.priority).then(function(ref){
{'fraction_non_alphanumeric': 0.11719412724306688, 'fraction_numerical': 0.0007830342577487765, 'mean_word_length': 1.7992694063926942, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3221793', 'n_tokens_mistral': 4296, 'n_tokens_neox': 4166, 'n_words': 858}