import React from 'react';
import { Rectangle } from 'recharts';
import theme from '../theme';
import { last } from 'rambda';

export default class Job extends React.PureComponent {
  render() {
    const {
      x,
      y,
      payload: {
        name,
        formerStartTime,
        formerEndTime,
        startTime,
        endTime,
        delayed
      },
      xAxis: {
        niceTicks,
        width: axisWidth
      }
    } = this.props;

    if (!endTime) return null;

    const duration = Math.abs(endTime - startTime);

    if (!duration) return null;

    const formerDuration = Math.abs(
      (typeof formerEndTime === 'undefined' ? endTime : formerEndTime)
      - (typeof formerStartTime === 'undefined' ? startTime : formerStartTime)
    );

    // const width = (axisWidth / (niceTicks.length - 1)) * duration;
    const width = (axisWidth / ((last(niceTicks) - niceTicks[0]) || 1)) * duration;
    const height = theme.gantt.job.height;

    // console.log(this.props.payload, axisWidth, niceTicks, duration);

    return (
      <JobBox
        x={x + 5}
        y={y + 5}
        width={width}
        height={height}
        duration={formerDuration}
        name={name}
        isDelayed={delayed}
      />
    );
  }
}

class JobBox extends React.PureComponent {
  render() {
    const { x, y, width, height } = this.props;
    let { duration, name, isDelayed } = this.props;

    const { stroke, textColor } = theme.gantt.job;

    const fill = isDelayed ? theme.gantt.job.fillError : theme.gantt.job.fill;

    return (
      <React.Fragment>
        <Rectangle x={x} y={y - (height / 2)} width={width} height={height} fill={fill} stroke={stroke} />
        <text x={x + 10} y={y - 9} alignmentBaseline="central" fill={textColor}>{duration}</text>
        <text x={x + 10} y={y + 9} alignmentBaseline="central" fill={textColor}>{name}</text>
      </React.Fragment>
    );
  }
}