import React, { PureComponent } from 'react';
import Form from './components/Form';
import Gantt from './components/Gantt';
import { normalizeData } from './ganttUtils';
import algorithms from './algorithms';
import { filter, flatten, identity, map, pluck, range, times } from 'rambda';
import uuid from 'uuid/v4';
import { selectAlgorithms, fastestResult, najneomeskanejsiResult } from './selectAlgorithm';

class App extends PureComponent {
  state = { ganttData: null };

  onFormSubmit = ({ preempt, flowShop, rows }) => {
    const algorithmNames = selectAlgorithms(rows, preempt, flowShop == '1');

    if (!algorithmNames) {
      alert('Pre zvolenú konfiguráciu sa nenašiel vhodný algoritmus');
      return;
    }

    console.log(algorithmNames);

    const results = map(algorithmName => {
      const algorithm = algorithms[algorithmName];

      let jobTimes;

      if (algorithmName === 'johnson' || algorithmName === 'palmer' || algorithmName === 'grupt' || algorithmName === 'campbel') {
        jobTimes = times(i => ({
          jobId: uuid(),
          operations: map(j =>
            rows[j].jobs[i] ? {
              t: rows[j].jobs[i].t,
              name: rows[j].jobs[i].name
            } : undefined, range(0, rows.length)
          )
        }), rows[0].jobs.length);
      } else if (algorithmName === 'mcnaught' || algorithmName === 'vahy') {
        jobTimes = flatten(pluck('jobs', rows));
        jobTimes = map(jobTime => ({
          ...jobTime,
          jobId: jobTime.id,
          anc: map(anc => anc.split(':')[1], jobTime.anc || []) }), jobTimes);
      } else {
        jobTimes = map(job => ({
          jobId: job.id,
          t: +job.t,
          d: +job.d,
          w: +job.w,
          name: job.name,
          anc: map(anc => anc.split(':')[1], job.anc || [])
        }), rows[0].jobs);
      }

      // console.log(jobTimes);
      // return;

      // console.log(rows[1].jobs);

      const result = algorithm(jobTimes, rows.length);
      console.log(result);
      return result;
    }, algorithmNames);

    const validResults = filter(identity, results);
    const fastestIndex = rows.length === 1
      ? najneomeskanejsiResult(validResults)
      : fastestResult(validResults);

    if (fastestIndex === -1) {
      alert('Nepodarilo sa násť rozvrh pre zvolenú konfiguráciu');
      return;
    }

    // console.log(fastestIndex, validResults);

    const ganttData = normalizeData(validResults[fastestIndex]);

    // console.log(validResults[fastestIndex]);

    this.setState({
      ganttData
    });
  };

  render() {
    const { ganttData } = this.state;

    return (
      <div style={{ padding: 20 }}>
        <Form onSubmit={this.onFormSubmit} />
        {ganttData && <Gantt data={ganttData}/>}
      </div>
    );
  }
}

export default App;