var $ = document.getElementById.bind(document);
import {Controller as Main} from '../src/main/main-controller';
import {getShortcutObject, metaKey} from './_util';
import {shortcuts as aceDefaultShortcuts} from './_aceDefaultShortcuts';
import atomic from 'atomic';
atomic = atomic(window);

const queryString = window.location.hash.replace(/^#\?/, '');

const onSave = () => main.onSave();

const getTestRunner = () => {
  var validTestRunners = ['mocha', 'jasmine'];
  var testRunner = queryString.match(/test-runner=(\w+)/);
  if (testRunner && testRunner.length === 2 && validTestRunners.indexOf(testRunner[1]) > -1) {
    return testRunner[1];
  }
  return 'mocha';
};

const getSourceCode = () => {

  var sourceCode = localStorage.getItem('code');
  if(sourceCode) {
    main.setEditorContent(sourceCode);
    return;
  }

  var kataUrl = getKataUrl();
  atomic.get(kataUrl)
    .success((data) => main.setEditorContent(data))
    .error((e, xhr) => {
      if (xhr.status === 404) {
        main.setEditorContent(`// 404, Kata at "${kataUrl}" not found\n// Maybe try a different kata (see URL).`);
      } else {
        main.setEditorContent('// not kata found :(');
      }
    });
};


const getKataUrl = () => {
  var kataName = queryString.match(/kata=([^&]+)/);
  if (kataName && kataName.length === 2) {
    kataName = kataName[1];
  } else {
    kataName = 'es5/mocha+assert/assert-api';
  }
  return `http://${process.env.KATAS_SERVICE_DOMAIN}/katas/${kataName}.js`;
};

getSourceCode();



const shortcuts = aceDefaultShortcuts.concat([
  getShortcutObject([metaKey, 'S'], onSave, 'Save+Run')
]);

var main = new Main($('tddbin'), {
  iframeSrcUrl: `./${getTestRunner()}/spec-runner.html`,
  shortcuts: shortcuts
});


@@ -698,16 +698,45 @@
 () =%3E %7B%0A
+  var kataUrl = getKataUrl();
 %0A  var s
@@ -781,16 +781,71 @@
 ');%0A  if
+ (kataUrl) %7B%0A    loadKataFromUrl(kataUrl);%0A  %7D else if 
 (sourceC
@@ -896,52 +896,285 @@
 ;%0A  
-  return;%0A  %7D%0A%0A  var kataUrl = getKataUrl();
+%7D else %7B%0A    loadDefaultKata();%0A  %7D%0A%7D;%0A%0Aconst loadDefaultKata = () =%3E %7B%0A  const kataName = 'es5/mocha+assert/assert-api';%0A  const kataUrl = %60http://$%7Bprocess.env.KATAS_SERVICE_DOMAIN%7D/katas/$%7BkataName%7D.js%60;%0A  loadKataFromUrl(kataUrl);%0A%7D;%0A%0Aconst loadKataFromUrl = (kataUrl) =%3E %7B
 %0A  a
@@ -1506,17 +1506,16 @@
 %7D);%0A%7D;%0A%0A
-%0A
 const ge
@@ -1662,67 +1662,8 @@
 ;%0A  
-%7D else %7B%0A    kataName = 'es5/mocha+assert/assert-api';%0A  %7D%0A
   re
@@ -1738,28 +1738,15 @@
 s%60;%0A
-%7D;%0A%0AgetSourceCode();
+  %7D%0A%7D;%0A
 %0A%0A%0A%0A
@@ -1969,12 +1969,29 @@
 rtcuts%0A%7D);%0A%0A
+getSourceCode();%0A

Implement the default behavior as it shall be.