<commit_before>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:true */
/*global  Backbone, Skeletor, _, jQuery, Rollcall, google, Paho */

(function() {
  "use strict";
  var Skeletor = this.Skeletor || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || new Skeletor.App();
  var Model = this.Skeletor.Model;
  Skeletor.Model = Model;
  var app = this.Skeletor.Mobile;


  app.config = null;
  app.requiredConfig = {
    drowsy: {
      url: 'string',
      db: 'string',
      username: 'string',
      password: '<PASSWORD>'
    },
    wakeful: {
      url: 'string'
    },
    login_picker:'boolean',
    runs:'object'
  };

  var DATABASE = null;

  app.rollcall = null;
  app.runId = null;
  app.runState = null;
  app.users = null;
  app.username = null;
  app.currentUser = null;
  app.lesson = null;
  app.contributions = [];
  app.shownContinueFlag = false;          // PUUUUUUKE

  app.homeView = null;
  app.definitionView = null;
  app.relationshipView = null;
  app.vettingView = null;

  app.keyCount = 0;
  app.autoSaveTimer = window.setTimeout(function() { }, 10);

  app.state = [];

  app.numVettingTasks = [];


  app.init = function() {
    /* CONFIG */
    app.loadConfig('../config.json');
    app.verifyConfig(app.config, app.requiredConfig);

    // Adding BasicAuth to the XHR header in order to authenticate with drowsy database
    // this is not really big security but a start
    var basicAuthHash = btoa(app.config.drowsy.username + ':' + app.config.drowsy.password);
    Backbone.$.ajaxSetup({
      beforeSend: function(xhr) {
        return xhr.setRequestHeader('Authorization',
          // 'Basic ' + btoa(username + ':' + password));
          'Basic ' + basicAuthHash);
      }
    });

    // hide all rows initially
    app.hideAllContainers();

    app.handleLogin();
  };

  app.handleLogin = function () {
    if (jQuery.url().param('runId') && jQuery.url().param('username')) {
      console.log ("URL parameter correct :)");
      app.runId = jQuery.url().param('runId');
      app.username = jQuery.url().param('username');
    } else {
      // retrieve user name from cookie if possible otherwise ask user to choose name
      app.runId = jQuery.cookie('brainstorm_mobile_runId');
      app.username = jQuery.cookie('brainstorm_mobile_username');
    }

    if (app.username && app.runId) {
      // We have a user in cookies so we show stuff
      console.log('We found user: '+app.username);

      // this needs runId
      setDatabaseAndRollcallCollection();

      // make sure the app.users collection is always filled
      app.rollcall.usersWithTags([app.runId])
      .done(function (usersInRun) {
        console.log(usersInRun);

        if (usersInRun && usersInRun.length > 0) {
          app.users = usersInRun;

          // sort the collection by username
          app.users.comparator = function(model) {
            return model.get('username');
          };
          app.users.sort();

          app.currentUser = app.users.findWhere({username: app.username});

          if (app.currentUser) {
            jQuery('.username-display a').text(app.runId+"'s class - "+app.currentUser.get('display_name'));

            hideLogin();
            showUsername();

            app.setup();
          } else {
            console.log('User '+usersInRun+' not found in run '+app.runId+'. Show login picker!');
            logoutUser();
          }
        } else {
          console.log("Either run is wrong or run has no users. Wrong URL or Cookie? Show login");
          // fill modal dialog with user login buttons
          logoutUser();
        }
      });
    } else {
      console.log('No user or run found so prompt for username and runId');
      hideUsername();
      // fill modal dialog with user login buttons
      if (app.config.login_picker) {
        hideLogin();
        showRunPicker();
      } else {
        showLogin();
        hideUserLoginPicker();
      }
    }

    // click listener that sets username
    jQuery('#login-button').click(function() {
      app.loginUser(jQuery('#username').val());
      // prevent bubbling events that lead to reload
      return false;
    });
  };

  app.setup = function() {
    Skeletor.Model.init(app.config.drowsy.url, DATABASE)
    .then(function () {
      console.log('Model initialized - now waking up');
      return Skeletor.Model.wake(app.config.wakeful.url);
    })
    .then(function() {
      // run state used for pausing/locking the tablet
      console.log('State model initialized - now waking up');
      app.runState = Skeletor.getState('RUN');
      app.runState.wake(app.config.wakeful.url);
      app.runState.on('change', app.reflectRunState);
    })
    .then(function() {
      var test = Skeletor.Smartboard.init(app.runId);
    })
    .done(function () {
      ready();
      console.log('Models are awake - now calling ready...');
    });
  };

  var ready = function() {
    checkDBValidity();
    buildConstants();
    setUpUI();
    setUpClickListeners();
    wireUpViews();
    app.hideAllContainers();
    jQuery('#home-screen').removeClass('hidden');
  };

  var checkDBValidity = function() {
    var validFlag = true;
    // for each lesson
    Skeletor.Model.awake.lessons.each(function(lesson) {
      var lessonNum = lesson.get('number');
      // skipping lesson 1, since that lesson is just for testing...
      if (lessonNum !== 1) {
        // go through all of the terms, check that each user has been assigned to is spelled correctly
        _.each(Skeletor.Model.awake.terms.where({"lesson": lessonNum}), function(term) {
          if (term.get('assigned_to') === "" || app.users.findWhere({"username": term.get('assigned_to')}) == null) {
            validFlag = false;
          }
          if (term.get('name') === "") {
            validFlag = false;
          }
          if (Skeletor.Model.awake.relationships.findWhere({"lesson": lessonNum, "from": term.get('name')}) == null &&
              Skeletor.Model.awake.relationships.findWhere({"lesson": lessonNum, "to": term.get('name')}) == null) {
            validFlag = false;
          }
        });
        _.each(Skeletor.Model.awake.relationships.where({"lesson": lessonNum}), function(relationship) {
          if (relationship.get('assigned_to') === "" || app.users.findWhere({"username": relationship.get('assigned_to')}) == null) {
            validFlag = false;
          }
          if (relationship.get('from') === "" || relationship.get('to') === "") {
            validFlag = false;
          }
          if (Skeletor.Model.awake.terms.findWhere({"name": relationship.get('from')}) == null ||
              Skeletor.Model.awake.terms.findWhere({"name": relationship.get('to')}) == null) {
            validFlag = false;
          }
        });
      }
    });

    if (validFlag) {
      console.log('DB validation passed!');
    } else {
      console.error('Did not pass DB validation');
    }
  };

  var buildConstants = function() {
    Skeletor.Model.awake.lessons.each(function(lesson) {
      app.numVettingTasks.push(lesson.get('vetting_tasks'));
    });
  };

  var setUpUI = function() {
    /* MISC */
    jQuery().toastmessage({
      position : 'middle-center'
    });<commit_msg>dbvalidation tests complete<commit_after>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:true */
/*global  Backbone, Skeletor, _, jQuery, Rollcall, google, Paho */

(function() {
  "use strict";
  var Skeletor = this.Skeletor || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || new Skeletor.App();
  var Model = this.Skeletor.Model;
  Skeletor.Model = Model;
  var app = this.Skeletor.Mobile;


  app.config = null;
  app.requiredConfig = {
    drowsy: {
      url: 'string',
      db: 'string',
      username: 'string',
      password: '<PASSWORD>'
    },
    wakeful: {
      url: 'string'
    },
    login_picker:'boolean',
    runs:'object'
  };

  var DATABASE = null;

  app.rollcall = null;
  app.runId = null;
  app.runState = null;
  app.users = null;
  app.username = null;
  app.currentUser = null;
  app.lesson = null;
  app.contributions = [];
  app.shownContinueFlag = false;          // PUUUUUUKE

  app.homeView = null;
  app.definitionView = null;
  app.relationshipView = null;
  app.vettingView = null;

  app.keyCount = 0;
  app.autoSaveTimer = window.setTimeout(function() { }, 10);

  app.state = [];

  app.numVettingTasks = [];


  app.init = function() {
    /* CONFIG */
    app.loadConfig('../config.json');
    app.verifyConfig(app.config, app.requiredConfig);

    // Adding BasicAuth to the XHR header in order to authenticate with drowsy database
    // this is not really big security but a start
    var basicAuthHash = btoa(app.config.drowsy.username + ':' + app.config.drowsy.password);
    Backbone.$.ajaxSetup({
      beforeSend: function(xhr) {
        return xhr.setRequestHeader('Authorization',
          // 'Basic ' + btoa(username + ':' + password));
          'Basic ' + basicAuthHash);
      }
    });

    // hide all rows initially
    app.hideAllContainers();

    app.handleLogin();
  };

  app.handleLogin = function () {
    if (jQuery.url().param('runId') && jQuery.url().param('username')) {
      console.log ("URL parameter correct :)");
      app.runId = jQuery.url().param('runId');
      app.username = jQuery.url().param('username');
    } else {
      // retrieve user name from cookie if possible otherwise ask user to choose name
      app.runId = jQuery.cookie('brainstorm_mobile_runId');
      app.username = jQuery.cookie('brainstorm_mobile_username');
    }

    if (app.username && app.runId) {
      // We have a user in cookies so we show stuff
      console.log('We found user: '+app.username);

      // this needs runId
      setDatabaseAndRollcallCollection();

      // make sure the app.users collection is always filled
      app.rollcall.usersWithTags([app.runId])
      .done(function (usersInRun) {
        console.log(usersInRun);

        if (usersInRun && usersInRun.length > 0) {
          app.users = usersInRun;

          // sort the collection by username
          app.users.comparator = function(model) {
            return model.get('username');
          };
          app.users.sort();

          app.currentUser = app.users.findWhere({username: app.username});

          if (app.currentUser) {
            jQuery('.username-display a').text(app.runId+"'s class - "+app.currentUser.get('display_name'));

            hideLogin();
            showUsername();

            app.setup();
          } else {
            console.log('User '+usersInRun+' not found in run '+app.runId+'. Show login picker!');
            logoutUser();
          }
        } else {
          console.log("Either run is wrong or run has no users. Wrong URL or Cookie? Show login");
          // fill modal dialog with user login buttons
          logoutUser();
        }
      });
    } else {
      console.log('No user or run found so prompt for username and runId');
      hideUsername();
      // fill modal dialog with user login buttons
      if (app.config.login_picker) {
        hideLogin();
        showRunPicker();
      } else {
        showLogin();
        hideUserLoginPicker();
      }
    }

    // click listener that sets username
    jQuery('#login-button').click(function() {
      app.loginUser(jQuery('#username').val());
      // prevent bubbling events that lead to reload
      return false;
    });
  };

  app.setup = function() {
    Skeletor.Model.init(app.config.drowsy.url, DATABASE)
    .then(function () {
      console.log('Model initialized - now waking up');
      return Skeletor.Model.wake(app.config.wakeful.url);
    })
    .then(function() {
      // run state used for pausing/locking the tablet
      console.log('State model initialized - now waking up');
      app.runState = Skeletor.getState('RUN');
      app.runState.wake(app.config.wakeful.url);
      app.runState.on('change', app.reflectRunState);
    })
    .then(function() {
      var test = Skeletor.Smartboard.init(app.runId);
    })
    .done(function () {
      ready();
      console.log('Models are awake - now calling ready...');
    });
  };

  var ready = function() {
    checkDBValidity();
    buildConstants();
    setUpUI();
    setUpClickListeners();
    wireUpViews();
    app.hideAllContainers();
    jQuery('#home-screen').removeClass('hidden');
  };

  var checkDBValidity = function() {
    var validFlag = true;
    var name, type;
    // for each lesson
    Skeletor.Model.awake.lessons.each(function(lesson) {
      var lessonNum = lesson.get('number');
      // skipping lesson 1, since that lesson is just for testing...
      if (lessonNum !== 1) {
        // go through all of the terms, check that each user has been assigned to is spelled correctly
        _.each(Skeletor.Model.awake.terms.where({"lesson": lessonNum}), function(term) {
          if (term.get('assigned_to') === "" || app.users.findWhere({"username": term.get('assigned_to')}) == null) {
            validFlag = false;
            name = term.get('name');
            type = "unassigned";
          }
          if (term.get('name') === "") {
            validFlag = false;
            name = term.get('name');
            type = "blank";
          }
          // make sure it exists in the relationships
          if (Skeletor.Model.awake.relationships.findWhere({"lesson": lessonNum, "from": term.get('name')}) == null &&
              Skeletor.Model.awake.relationships.findWhere({"lesson": lessonNum, "to": term.get('name')}) == null) {
            validFlag = false;
            name = term.get('name');
            type = "missing from relationships";
          }
        });
        // go through all of the relationships, check that each user has been assigned to is spelled correctly
        _.each(Skeletor.Model.awake.relationships.where({"lesson": lessonNum}), function(relationship) {
          if (relationship.get('assigned_to') === "" || app.users.findWhere({"username": relationship.get('assigned_to')}) == null) {
            validFlag = false;
            name = relationship.get('from');
            type = "unassigned";
          }
          if (relationship.get('from') === "" || relationship.get('to') === "") {
            validFlag = false;
            name = relationship.get('from');
            type = "blank";
          }
          // make sure it exists in the terms
          if (Skeletor.Model.awake.terms.findWhere({"name": relationship.get('from')}) == null ||
              Skeletor.Model.awake.terms.findWhere({"name": relationship.get('to')}) == null) {
            validFlag = false;
            name = relationship.get('from');
            type = "missing from terms";
          }
        });
      }
    });

    if (validFlag) {
      console.log('DB validation passed!');
    } else {
      console.error('Did not pass DB validation. ' + name + ' is ' + type);
    }
  };

  var buildConstants = function() {
    Skeletor.Model.awake.lessons.each(function(lesson) {
      app.numVettingTasks.push(lesson.get('vetting_tasks'));
    });
  };

  var setUpUI = function() {
    /* MISC */
    jQuery().toastmessage({
      position : 'middle-center'
    });
{'fraction_non_alphanumeric': 0.1475974025974026, 'fraction_numerical': 0.0007792207792207792, 'mean_word_length': 2.398278905560459, 'pattern_counts': {'":': 20, '<': 5, '<?xml version=': 0, '>': 7, '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': '6460195', 'n_tokens_mistral': 4735, 'n_tokens_neox': 4589, 'n_words': 1029}