'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

require('./App.css');

var _testCodeData = require('./testCodeData');

var _CodeTester = require('./components/CodeTester/CodeTester');

var _CodeTester2 = _interopRequireDefault(_CodeTester);

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-unused-vars: 0 */


/**
 * <CodeTester />
 * React text editor component which auto run code against provided Mocha tests.
 * @param {String} code: The initial code in the text editor.
 * @param {Function} onValidCode: Function that is run if the text editor code passes
 * all linting rules.
 * @param {Function} onAnyCode: Function run on any input to the text editor.
 */

var App = function (_Component) {
  _inherits(App, _Component);

  function App(props) {
    _classCallCheck(this, App);

    var _this = _possibleConstructorReturn(this, (App.__proto__ || Object.getPrototypeOf(App)).call(this, props));

    _this.state = { testSpec: '', starterCode: '', loading: true, boilerplate: '', instructions: '', editMode: false };
    _this.renderTester = _this.renderTester.bind(_this);
    _this.handleUrlInput = _this.handleUrlInput.bind(_this);
    _this.handleInstructionsChange = _this.handleInstructionsChange.bind(_this);
    _this.handleTestSpecChange = _this.handleTestSpecChange.bind(_this);
    _this.handleBoilerplateChange = _this.handleBoilerplateChange.bind(_this);
    _this.handleEditModeChange = _this.handleEditModeChange.bind(_this);
    _this.handleGithubSubmit = _this.handleGithubSubmit.bind(_this);
    return _this;
  }

  _createClass(App, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      if (process.env.NODE_ENV === 'development') {
        var fakeSubmitEvent = { preventDefault: function preventDefault() {}, target: { 'code-quiz-url': { value: 'http://localhost:8080/code-quiz-immersion-precourse/exit/' } } };
        this.handleUrlInput(fakeSubmitEvent);
      }
    }
  }, {
    key: 'handleEditModeChange',
    value: function handleEditModeChange() {
      this.setState(function (_ref) {
        var editMode = _ref.editMode;

        return { editMode: !editMode };
      });
    }
  }, {
    key: 'handleUrlInput',
    value: function handleUrlInput(event) {
      var _this2 = this;

      event.preventDefault();
      var url = event.target['code-quiz-url'].value;
      getPublicCodeQuiz(url).then(function (data) {
        _this2.setState({
          testSpec: data.spec.data,
          loading: false,
          boilerplate: data.boilerplate.data,
          instructions: data.instructions.data,
          error: null
        });
      }).catch(function (err) {
        console.error(err);
        _this2.setState({
          testSpec: '',
          loading: false,
          boilerplate: 'Error loading data...',
          error: err
        });
      });
    }
  }, {
    key: 'handleInstructionsChange',
    value: function handleInstructionsChange(instructions) {
      this.setState({ instructions: instructions });
    }
  }, {
    key: 'handleTestSpecChange',
    value: function handleTestSpecChange(testSpec) {
      this.setState({ testSpec: testSpec });
    }
  }, {
    key: 'handleBoilerplateChange',
    value: function handleBoilerplateChange(boilerplate) {
      this.setState({ boilerplate: boilerplate });
    }
  }, {
    key: 'handleGithubSubmit',
    value: function handleGithubSubmit() {
      console.log('This will commit to GitHub repo in future.');
    }
  }, {
    key: 'renderTester',
    value: function renderTester() {
      var handleTestResults = function handleTestResults(passCount, failCount, runTime) {
        // console.log(passCount, failCount, runTime);
      };

      var handleLintedCode = function handleLintedCode(lintedCode) {};

      var handleAnyCode = function handleAnyCode(code) {};
      var _state = this.state,
          boilerplate = _state.boilerplate,
          instructions = _state.instructions,
          editMode = _state.editMode;

      var testSpec = '';
      if (this.state.testSpec.length) testSpec = this.state.testSpec;
      return _react2.default.createElement(_CodeTester2.default, {
        initialCode: boilerplate,
        instructions: instructions,
        iFrameUrl: '/test-runner.html',
        testHandlerUrl: '/get_results.js',
        onAnyCode: handleAnyCode,
        onLintedCode: handleLintedCode,
        onTestResults: handleTestResults,
        showLints: true,
        testSpec: testSpec,
        handleInstructionsChange: this.handleInstructionsChange,
        handleTestSpecChange: this.handleTestSpecChange,
        handleBoilerplateChange: this.handleBoilerplateChange,
        editMode: editMode,
        infiniteLoopTimeout: 500
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var codeQuizUrl = this.props.codeQuizUrl;
      var error = this.state.error;

      return _react2.default.createElement(
        'div',
        { className: 'container-fluid' },
        _react2.default.createElement(
          'div',
          { className: 'row' },
          _react2.default.createElement(
            'div',
            { className: 'col-md-8' },
            _react2.default.createElement(
              'form',
              { className: 'form-inline', onSubmit: this.handleUrlInput },
              _react2.default.createElement(
                'div',
                { className: 'form-group' },
                _react2.default.createElement(
                  'label',
                  { htmlFor: 'inlineFormInput' },
                  'Enter CodeQuiz Url'
                ),
                _react2.default.createElement('input', { className: 'form-control', name: 'code-quiz-url', size: '50' })
              ),
              _react2.default.createElement(
                'div',
                { className: 'checkbox' },
                _react2.default.createElement(
                  'label',
                  { className: 'form-check-label' },
                  _react2.default.createElement('input', { className: 'form-check-input', type: 'checkbox', onChange: this.handleEditModeChange }),
                  ' Edit Mode'
                )
              )
            )
          ),
          _react2.default.createElement(
            'div',
            { className: 'col-md-4' },
            _react2.default.createElement(
              'button',
              { className: 'btn btn-success pull-right', onClick: this.handleGithubSubmit },
              'Commit to GitHub'
            )
          )
        ),
        error ? _react2.default.createElement(
          'div',
          { className: 'row' },
          'Error loading data from ',
          codeQuizUrl,
          ':',
          error.message
        ) : _react2.default.createElement(
          'div',
          { className: 'row' },
          this.renderTester()
        )
      );
    }
  }]);

  return App;
}(_react.Component);

function getPublicCodeQuiz(codeQuizUrl) {
  var isTestMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

  return _bluebird2.default.join(getPublicResource(codeQuizUrl, 'index.js', isTestMode), getPublicResource(codeQuizUrl, 'README.md', isTestMode), getPublicResource(codeQuizUrl, 'index.spec.js', isTestMode), function (boilerplate, instructions, spec) {
    return { boilerplate: boilerplate, instructions: instructions, spec: spec };
  });

  function getPublicResource(projectPath, filename, isTestMode) {
    var url = void 0;
    if (isTestMode) {
      url = projectPath.replace(/\/+$/, '') + '/' + filename;
    } else {
      var parts = parseCodeQuizUrl(projectPath);
      url = 'https://raw.githubusercontent.com/OperationSpark/' + parts.repo + '/master' + parts.codeQuizPath + '/' + filename;
    }
    return _axios2.default.get(url);
  }
}

exports.default = App;