/* eslint-disable react/no-array-index-key */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import FontAwesome from 'react-fontawesome';
import _ from 'lodash';

import './Console.css';
import { defaultFunc } from '../CodeTester/helpers';

const hasErrors = logs => _.some(logs, { type: 'error' });

class Console extends Component {
  constructor(props) {
    super(props);
    this.handleErrors = this.handleErrors.bind(this);
    this.handleKeyUp = this.handleKeyUp.bind(this);
    this.renderLogs = this.renderLogs.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.logs.length === nextProps.logs.length) return;
    this.handleErrors(nextProps);
  }

  handleErrors({ onError, logs, show }) {
    !show && hasErrors(logs) && onError();
  }

  handleKeyUp(e) {
    // esc key
    if (e.keyCode === 27) {
      this.props.onToggleConsole();
    }
  }

  renderLogs(logs) {
    return logs.map(({ log, type }, i) => (
      <div key={`div-${i}`}>
        <pre className={`console-${type}`} key={`pre-${i}`}>
          {type === 'error' && 'Error: '}{log}
        </pre>
      </div>
    ));
  }

  render() {
    const { logs, show, onToggleConsole, style } = this.props;
    return (
      <div className="console-container" style={style}>
        <div
          className="console-close"
          id="console-close"
          onClick={onToggleConsole}
          role="button"
          tabIndex={0}
          onKeyUp={this.handleKeyUp}
        >
          <FontAwesome
            name={show ? 'toggle-right' : 'toggle-left'}
            className={show ? 'toggle-right' : 'toggle-left'}
          />
        </div>
        <div className="console-title">Console</div>
        <div className="console-logs">{this.renderLogs(logs)}</div>
      </div>
    );
  }
}

Console.propTypes = {
  // eslint-disable-next-line
  style: PropTypes.object,
  logs: PropTypes.arrayOf(PropTypes.shape({
    log: PropTypes.string,
    type: PropTypes.string,
  })),
  show: PropTypes.bool,
  onToggleConsole: PropTypes.func,
  // eslint-disable-next-line
  onError: PropTypes.func,
};

Console.defaultProps = {
  style: {},
  logs: [],
  show: false,
  onToggleConsole: defaultFunc,
  onError: defaultFunc
};

export default Console;
