
'use strict';

/* Action type constants. */
export const RUN_TEST = 'RUN_TEST';
export const CODE_CHANGED = 'CODE_CHANGED';
export const TESTS_STARTED = 'TESTS_STARTED';
export const TESTS_FINISHED = 'TESTS_FINISHED';
export const START_CHALLENGE = 'START_CHALLENGE';


/* Thunk action which runs the test cases against user code. */
export function runTests(userCode, currChallenge) {
  return function(dispatch) {
    dispatch(actionTestsStarted());

    // Eval user code inside worker
    // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766
    function createWorker () {
      return new Promise((resolve, reject) => {
        const wk = new Worker('../../public/js/worker.bundle.js');
        //wk.postMessage([userCode, currChallenge]);
        wk.postMessage([userCode, currChallenge]);
        wk.onmessage = e => {
          console.log(`worker onmessage result: ${e.data}`);
          resolve(e.data);
        };
      });
    }

    createWorker()
      .then(testResults => {
        dispatch(actionTestsFinished(testResults));
      });
  };
}

/* Dispatched when a user starts running the tests.*/
export function actionTestsStarted() {
  return {
    type: TESTS_STARTED
  };
}

/* Dispatched when the tests finish. */
export function actionTestsFinished(testResults) {
  return {
    type: TESTS_FINISHED,
    testResults
  };
}

export function startChallenge() {
  return {
    type: START_CHALLENGE
  };
}

export function onCodeChange(newCode) {
  return {
    type: CODE_CHANGED,
    code: newCode
  };
}


@@ -114,24 +114,72 @@
 E_CHANGED';%0A
+export const OUTPUT_CHANGED = 'OUTPUT_CHANGED';%0A
 export const
@@ -208,24 +208,24 @@
 S_STARTED';%0A
-
 export const
@@ -811,61 +811,8 @@
 ');%0A
-        //wk.postMessage(%5BuserCode, currChallenge%5D);%0A
     
@@ -1039,76 +1039,224 @@
 hen(
-testResults =%3E %7B%0A        dispatch(actionTestsFinished(testResults));
+workerData =%3E %7B%0A        dispatch(onOutputChange(workerData%5B0%5D.output));%0A        if (workerData.length %3E 1) %7B%0A          dispatch(actionTestsFinished(workerData.slice(1)));%0A        %7D%0A        else %7B%0A          %0A        %7D
 %0A   
@@ -1731,16 +1731,130 @@
 newCode%0A  %7D;%0A%7D%0A%0A
+export function onOutputChange(newOutput) %7B%0A  return %7B%0A    type: OUTPUT_CHANGED,%0A    userOutput: newOutput%0A  %7D;%0A%7D%0A

add action for handling user output change