'use strict';

var React = require('react');
var { connect } = require('react-redux');

var { Display } = require('renderer');

var { setWindowSize, addLine, removeLine, newTrack } = require('../actions');
var Editor = require('./Editor');

var makeRandomLine = require('../../test/makeRandomLine');
var _ = require('lodash');

function randomLines() {
  var lines = [];
  var limits = 900;
  var numLines = 500;

  for (let i = 0; i < 2 * numLines; i++) {
    lines.push(makeRandomLine(limits, 2));
  }
  return lines;
}

var randomTrack = randomLines();

var BLOCK_CONTEXT_MENU = true;

var App = React.createClass({

  componentDidMount() {
    this.interval = setInterval(this.onResize, 100);

    let track = this.props.trackData.track;
    let numLoadingFrames = 60;
    let numLinesPerFrame = Math.ceil(randomTrack.length / numLoadingFrames);
    let dispatch = this.props.dispatch;
    (function delayAddLine(n) {
      if (n >= randomTrack.length) {

        randomTrack = _.shuffle(track.getLines());

        (function delayRemoveLine(n) {
          if (n >= randomTrack.length / 2) {
            return
          }
          dispatch(removeLine(_.slice(randomTrack, n, n + numLinesPerFrame)))
          requestAnimationFrame(() => delayRemoveLine(n + numLinesPerFrame))
        })(0)

        return
      }
      dispatch(addLine(_.slice(randomTrack, n, n + numLinesPerFrame)))
      requestAnimationFrame(() => delayAddLine(n + numLinesPerFrame))
    })(0)
  },

  componentWillUnmount() {
    clearInterval(this.interval);
  },

  onResize() {
    let {
      width: prevWidth,
      height: prevHeight
    } = this.props.windowSize;
    // let {width, height} = this.container.getBoundingClientRect();
    let {
      innerWidth: width,
      innerHeight: height
    } = window;

    if (width > 0 && height > 0 && width !== prevWidth || height !== prevHeight) {
      this.props.dispatch(setWindowSize({width, height}));
    }
  },

  // TODO: move this out of App into selector i guess???
  getCam(playing, track, index, cam, width, height) {
    if (!playing) {
      return cam
    }
    let maxRadius = Math.max(cam.z * (Math.min(width, height) / 2) - 15)
    let {x, y} = track.getRiderCam(index, maxRadius)
    return {x, y, z: cam.z}
  },

  render() {
    let {
      dispatch,
      windowSize: {
        width,
        height
      },
      toolbars,
      cam,
      playback,
      playing,
      trackData: {
        track,
      },
      fileLoader
    } = this.props;

    // let maxRadius = Math.max(cam.z * (Math.min(width, height) / 2) - 15);
    // let {x, y} = getRiderCam(randomTrack, playback.index, maxRadius);
    // move logic to selector maybe i think ???
    return (
      <div
        className='main'
        ref={component => this.container = React.findDOMNode(component)}
        onContextMenu={e => BLOCK_CONTEXT_MENU ? e.preventDefault() : null}
      >
        <Display
          frame={playback.index}
          startPosition={track.getStartPosition()}
          viewOptions={{ color: !playing, floor: true }}
          rider={track.getRiderStateAtFrame(playback.index)}
          cam={this.getCam(playing, track, playback.index, cam, width, height)}
          lines={track.getLines()}
          width={width}
          height={height}
        />
        <Editor dispatch={dispatch} {...toolbars} fileLoader={fileLoader} playing={playing}/>
      </div>
    );
  }
});

function select({
  toolbars: {tool, ...toolbars},
  toggled,
  editorCamera,
  playback,
  ...state
}) {
  return {...state,
    toolbars: {...toolbars,
      selected: {
        ...toggled,
        [tool]: true,
        [playback.state]: playback.state !== 'stop'
      }
    },
    playing: playback.state !== 'stop' && playback.state !== 'pause',
    playback,
    cam: editorCamera,
  };
}

module.exports = connect(select)(App);

@@ -2013,95 +2013,316 @@
 Cam(
-playing, track, index, cam, width, height) %7B%0A    if (!playing) %7B%0A      return cam%0A    %7D
+) %7B%0A    let %7B%0A      windowSize: %7B%0A        width,%0A        height%0A      %7D,%0A      cam,%0A      playback: %7B%0A        index%0A      %7D,%0A      playing,%0A      trackData: %7B%0A        track,%0A      %7D,%0A    %7D = this.props;%0A    if (!playing) %7B%0A      return cam%0A    %7D%0A    let offset = 25; // TODO: make this responsive to toolbars
 %0A   
@@ -2387,18 +2387,22 @@
  / 2) - 
-15
+offset
 )%0A    le
@@ -2482,16 +2482,441 @@
 %7D%0A  %7D,%0A%0A
+  getViewBox() %7B%0A    let %7B%0A      windowSize: %7B%0A        width: w,%0A        height: h%0A      %7D%0A    %7D = this.props;%0A    let %7Bx, y, z%7D = this.getCam();%0A    return %5B%0A      x - w / 2 * z,%0A      y - h / 2 * z,%0A      w * z,%0A      h * z%0A    %5D;%0A  %7D,%0A%0A  getLines() %7B%0A    let %5Bx1, y1, w, h%5D = this.getViewBox();%0A    // console.log(x1, y1, x1 + w, y1 + h);%0A    return this.props.trackData.track.getLinesInBox(x1, y1, x1 + w, y1 + h);%0A  %7D,%0A%0A
   render
@@ -3798,58 +3798,8 @@
 Cam(
-playing, track, playback.index, cam, width, height
 )%7D%0A 
@@ -3815,20 +3815,19 @@
 lines=%7Bt
-rack
+his
 .getLine

implement rendering lines only in viewport