import React from 'react';
import ReactMarkdown from 'react-markdown';
import { Link } from 'react-router-dom';
import { intro } from '../resources/const';
const markdown = require('../resources/markdown.json');

const getHandleId = (() => {
  let id = 0;
  return () => ('handle-' + (++id));
})();
console.log(getHandleId(), getHandleId());

function getSectionLinks() {
  return (
    <ul>
    {markdown.map((section, sIndex) => (
      <li key={sIndex}><Link to={section.path}>{section.title}</Link></li>
    ))}
    </ul>
  );
}

const tutos = [
  { title: 'JavaScript', items: markdown
  // [
  //   { title: 'pouet', items: [
  //     { title: 'pouet child', items: [] }
  //   ] },
  //   { title: 'popop', items: [] },
  //   { title: 'douap', items: [] }
  // ]
},
  { title: 'jQuery', items: [] },
  { title: 'AngularJS', items: [] },
  { title: 'React', items: [] }
];
console.log(tutos);

class Tree extends React.Component {
  constructor(props) {
    super(props);
    this.onDragStart = this.onDragStart.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.state = {
      draggedItem: null,
      draggedOver: null
    };
  }

  onDragStart(draggedItem) {
    console.log('tree.onDragStart', draggedItem, this);
    const { draggedOver } = this.state;
    this.setState((prevState, props) => ({
      draggedItem, draggedOver
    }));
  }

  onDragOver(draggedOver) {
    console.log('tree.onDragOver', draggedOver, this);
    const { draggedItem } = this.state;
    this.setState((prevState, props) => ({
      draggedItem, draggedOver
    }));
  }

  render() {
    const { items } = this.props;
    const { draggedItem, draggedOver } = this.state;
    return (
      <div>
        {(! draggedItem) ? 'X' : draggedItem.props.path} |
        {(! draggedOver) ? 'Y' : draggedOver.props.path}
        {items.map((item, i) =>
          <TreeNode tree={this} item={item} key={item.title} index={i} path={i} level={0} />
        )}
      </div>
    );
  }
}

/*
 * get DOM ref    =>  https://reactjs.org/docs/refs-and-the-dom.html
 * dnd w/ handle  =>  https://github.com/jdiamond/html5-examples/blob/master/drag-and-drop/drag-handle.html
 */
class TreeNode extends React.Component {
  constructor(props) {
    super(props);
    this.onMouseDown = this.onMouseDown.bind(this);
    this.onDragStart = this.onDragStart.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.state = {
      dragged: false, dragOver: false, aboveMidLine: false
    };
    this.hid = getHandleId();
    console.log('TreeNode', this.props.path, this.props.item.title)

    this.drags = 0;
  }

  onMouseDown(e) {
    this.dragTarget = e.target;
  }

  onDragStart(e) {
    e.stopPropagation();
    if(! this.props.item.dragTo) {
      e.preventDefault();
      return;
    }
    
    const { draggable } = this;
    var handle = draggable.getElementsByClassName('drag-handle')[0];
    console.log('onDragStart', handle, draggable);
    if (handle.contains(this.dragTarget)) {
      e.dataTransfer.setData('text/plain', handle.id);
      this.props.tree.onDragStart(this);
      const { dragOver, aboveMidLine } = this.state;

      this.setState({
        dragged: true, dragOver, aboveMidLine
      });


    } else {
      e.preventDefault();
    }
  }

  onDragOver(e) {
    e.stopPropagation();
     // 'drag-over';
    const coordKeys = Object.keys(e).filter(k => k.match(/^[a-z]+(X|Y)$/));
    // coordKeys.forEach(k => console.log(k, '=>', e[k]));
    console.log('dragover', e.target, e.currentTarget, e.relatedTarget, e.dataTransfer); //, this.state.dragOver, this.props.item.title,
      // var domRect = element.getBoundingClientRect();var domRect = element.getBoundingClientRect(); );
    const { pageY } = e;
    const aboveMidLine = pageY < this.draggableMidLine;
    // console.log(aboveMidLine);


this.props.tree.onDragOver(this);

    const { dragged } = this.state;
// console.log(this.draggable, e.target);
//     if(this.draggable !== e.target) return;
    // this.setState({
    //   dragged, dragOver: true, aboveMidLine
    // });
    console.log(this.props.index);


    this.scheduleDragOverChange(1);
  }

  scheduleDragOverChange(change) {
    // const setState = this.setState.bind(this);
    const self = this;
    if(this.timeout) {
      clearTimeout(this.timeout);
    }
    this.drags += change;
    // const { dragged, dragOver,  }
    this.timeout = setTimeout(() => {
      console.log('drags change/total', change, self.drags)
      this.setState({
        dragOver: self.drags > 0
      });
    }, 100);
  }

  componentDidMount() {
    const { y, height } = this.draggable.getBoundingClientRect();
    this.draggableMidLine = y + (height / 2);
  }

  onDragLeave(e) {
    e.stopPropagation();
      // this.setState({
      //   dragOver: false
      // });
      this.scheduleDragOverChange(-1);
    // console.log(e.pageY);
    // this.dragOver = '';
    // console.log('dragleave', this.state.dragOver);
  }

  render() {
    const { title, items } = this.props.item;
    const { tree, path, level } = this.props;
    const { dragOver, aboveMidLine } = this.state;
    const paddingLeft = (level * 15) + 'px';
    const dragPlaceholderStyles = {
      minHeight: '39px', border: '1px dashed blue'
    }
    return (
      <div draggable
        ref={(div) => { this.draggable = div; }}
          className={ "tree-node" + (dragOver ? ' drag-over' : '') }
          style={{ paddingLeft }}
          onMouseDown={this.onMouseDown}
          onDragStart={this.onDragStart}
          onDragEnter={this.onDragOver}
          onDragLeave={this.onDragLeave}>
        <h5><i id={ this.hid } className="material-icons drag-handle">drag_handle</i><span>{ title }</span></h5>
        {(items || []).map((item, i) =>
          <TreeNode tree={tree} item={item} index={i} key={item.title} path={ path + '.' + i} level={level + 1} />
        )}
      {this.state.dragOver ? <div style={dragPlaceholderStyles}></div> : ''}
      </div>
    );
  }
}

class Home extends React.Component {
  render() {
    return (
      <div className="page">
        <div className="breadcrumb-wrapper">
          <span className="breadcrumb light-blue-text"><i className="material-icons">home</i></span>
          <span className="breadcrumb grey-text">Accueil</span>
        </div>

        <Tree items={tutos} />
      </div>
    );
  }
}

export default Home;
