/* eslint no-unused-vars: 0 */
import React, { Component } from 'react';
import './App.css';
import { eslintTest as starterCode, tests } from './testCodeData';
import CodeTester from './components/CodeTester/CodeTester';
import axios from 'axios';
import P from 'bluebird';
import PropTypes from 'prop-types';

/**
 * <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.
 */

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { testSpec: '', starterCode: '', loading: true, boilerplate: '', instructions: '' };
    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.handleGithubSubmit = this.handleGithubSubmit.bind(this);
    this.handleReset = this.handleReset.bind(this);
  }

  componentDidMount() {
    const { NODE_ENV, INITIAL_CODE_QUIZ } = process.env;
    if (NODE_ENV === 'development') {
      const fakeSubmitEvent = { preventDefault: () => { }, target: { 'code-quiz-url': { value: INITIAL_CODE_QUIZ || 'http://127.0.0.1:8080/checkpoints/javascript/checkpoint2/v2/' } }};
      this.handleUrlInput(fakeSubmitEvent);
    }
  }

  handleUrlInput(event) {
    event.preventDefault();
    const url = event.target['code-quiz-url'].value;
    getPublicCodeQuiz(url)
      .then(data => {
        this.setState({
          testSpec: data.spec.data,
          loading: false,
          boilerplate: data.boilerplate.data,
          instructions: data.instructions.data,
          error: null,
        });
      })
      .catch((err) => {
        console.error(err);
        this.setState({
          testSpec: '',
          loading: false,
          boilerplate: 'Error loading data...',
          error: err,
        });
      });
  }

  handleInstructionsChange(instructions) {
    this.setState({ instructions });
  }

  handleTestSpecChange(testSpec) {
    this.setState({ testSpec });
  }

  handleBoilerplateChange(boilerplate) {
    this.setState({ boilerplate });
  }

  handleGithubSubmit(commitMessage) {
    
  }

  handleReset() {
  }

  renderTester() {
    const handleTestResults = (passCount, failCount, runTime) => {
      // console.log(passCount, failCount, runTime);
    };

    const handleLintedCode = (lintedCode) => {};

    const handleAnyCode = (code) => {};
    const { boilerplate, instructions, editMode } = this.state;
    let testSpec = '';
    if (this.state.testSpec.length) testSpec = this.state.testSpec;
    return (
      <CodeTester
        handleUrlInput={this.handleUrlInput}
        handleGithubSubmit={this.handleGithubSubmit}
        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
        toggleEditMode={this.handleEditModeChange}
        showConsole={false}
        handleReset={this.handleReset}
        headerText="Header"
        subHeaderText="sub header"
      />
    );
  }

  renderErrorScreen(error) {
    return (
      <div className="blackout">
        <div className="blackout-content">
          <h2>There was an error.</h2>
          <h1>Grab your teacher.</h1>
          <code>{error.message}</code>
        </div>
      </div>
    );
  }

  render () {
    const { codeQuizUrl } = this.props;
    const { error } = this.state;
    return (
      <div className="container-fluid">
        {error ?
          (<div className="row">
            {/* {this.renderTester()} */}
            {this.renderErrorScreen(error)}
          </div>) :
          (<div className="row">
            {this.renderTester()}
          </div>)
        }
      </div>
    );
  }
}

function getPublicCodeQuiz(codeQuizUrl, isTestMode = true) {
  return P.join(
    getPublicResource(codeQuizUrl, 'index.js', isTestMode),
    getPublicResource(codeQuizUrl, 'README.md', isTestMode),
    getPublicResource(codeQuizUrl, 'index.spec.js', isTestMode),
    (boilerplate, instructions, spec) => {
      return { boilerplate, instructions, spec };
    }
  );

  function getPublicResource(projectPath, filename, isTestMode) {
    const url = `${projectPath.replace(/\/+$/, '')}/${filename}`;
    return axios.get(url);
  }
}

App.propTypes = {
  codeQuizUrl: PropTypes.string,
};

export default App;
