'use strict';

angular.module('core').controller('StartController', ['$scope', '$http', '$timeout', 'TrialData',
  function($scope, $http, $timeout, TrialData) {

    /**
     * Controller sequence of events:
     *
     * 1. Reset TrialData
     * 2. Send message to reset experiment: /eim/control/reset
     * 2. Wait for message: /eim/status/resetComplete
     * 3. Generate a new session ID
     * 4. Store session ID in TrialData
     * 5. Request experiment setup from backend
     * 6. Wait for message: /eim/status/experimentReady
     * 7.
     *
     * TODO: Update sequence
     */

    // Are all pieces of experiment ready to begin?
    $scope.maxReady = false;
    $scope.backendReady = false;
    $scope.readyToAdvance = function() {
      if ($scope.debugMode) {
        return true;
      } else {
        return $scope.maxReady && $scope.backendReady;
      }
    };

    // Reset TrialData
    TrialData.reset();

    // Setup socket
    /* global io */
    var socket = io();

    // Generate new session identifier
    /* global UUID */
    var sessionID = UUID.generate();
    TrialData.data.metadata.session_number = sessionID;

    // Setup OSC 'message sent' logger
    socket.on('oscMessageSent', function(data) {
      console.log('socket "oscMessageSent" event received with data: ' + data);
    });

    // Configure handlers for incoming OSC messages
    socket.on('oscMessageReceived', function(data) {

      // If we received the resetComplete message
      if (data.address === '/eim/status/startExperiment') {
        $scope.$apply(function() {
          $scope.maxReady = true;
        });
      }
    });

    // Get a new experiment setup from the backend
    $http.get('/api/experiment-schemas/random')
      .success(function(data) {

        // Send experiment start message
        socket.emit('sendOSCMessage', {
          oscType: 'message',
          address: '/eim/control/startExperiment',
          args: {
            type: 'string',
            value: TrialData.data.metadata.session_number
          }
        });

        for (var i in data.media) {
          TrialData.data.media.push(data.media[i].label);
        }

        // Only proceed if we've got some media!
        if (data.media.length > 0) {
            $scope.backendReady = true;
        } else {
          $scope.addGenericErrorAlert();
          throw new Error('No media was found in the fetched experiment schema');
        }
      })
      .error(function(data) {
        $scope.addGenericErrorAlert();
        throw new Error('An experiment schema could not be fetched from the server');
      });

    // If we aren't ready to go after 10 seconds, throw an error
    $timeout(function() {
      if (!$scope.readyToAdvance()) {
        $scope.addGenericErrorAlert();
        throw new Error('The experiment was not setup after 10 seconds');
      }
    }, 10000);
  }
]);
@@ -160,439 +160,8 @@
  %7B%0A%0A
-    /**%0A     * Controller sequence of events:%0A     *%0A     * 1. Reset TrialData%0A     * 2. Send message to reset experiment: /eim/control/reset%0A     * 2. Wait for message: /eim/status/resetComplete%0A     * 3. Generate a new session ID%0A     * 4. Store session ID in TrialData%0A     * 5. Request experiment setup from backend%0A     * 6. Wait for message: /eim/status/experimentReady%0A     * 7.%0A     *%0A     * TODO: Update sequence%0A     */%0A%0A
     
@@ -597,16 +597,42 @@
 entifier
+ and store it in TrialData
 %0A    /* 
@@ -751,245 +751,153 @@
  // 
-Setup
+Configure handler for incoming
  OSC 
-'
 message
- sent' logger%0A    socket.on('oscMessageSent', function(data) %7B%0A      console.log('socket %22oscMessageSent%22 event received with data: ' + data);%0A    %7D);%0A%0A    // Configure handlers for incoming OSC messages%0A    socket.on('
+s%0A    var oscMessageReceivedListener = function(data) %7B%0A      console.log('start.client.controller.js: 
 oscM
@@ -915,26 +915,10 @@
 ved'
-, function(data) %7B
+);
 %0A%0A  
@@ -1005,22 +1005,17 @@
 /status/
-startE
+e
 xperimen
@@ -1015,16 +1015,21 @@
 periment
+Ready
 ') %7B%0A   
@@ -1110,24 +1110,372 @@
 %7D);%0A      %7D%0A
+    %7D;%0A%0A    // Attach handler for incoming OSC messages%0A    socket.on('oscMessageReceived', oscMessageReceivedListener);%0A%0A    // Destroy handler for incoming OSC messages when $scope is destroyed%0A    $scope.$on('$destroy', function removeOSCMessageReceivedListener() %7B%0A      socket.removeListener('oscMessageReceived', oscMessageReceivedListener);%0A
     %7D);%0A%0A   
@@ -1890,24 +1890,67 @@
        %7D);%0A%0A
+        // Add received media to TrialData%0A
         for 

Remove event listeners on scope destruction in StartController