import React, {Component} from 'react';
import PropTypes, { element } from 'prop-types';
import Panel from './panel';
import {
  MODE_IDLE, MODE_2D_ZOOM_IN, MODE_2D_ZOOM_OUT, MODE_2D_PAN, MODE_3D_VIEW, MODE_3D_FIRST_PERSON,
  MODE_WAITING_DRAWING_LINE, MODE_DRAWING_LINE, MODE_DRAWING_HOLE, MODE_DRAWING_ITEM, MODE_DRAGGING_LINE,
  MODE_DRAGGING_VERTEX, MODE_DRAGGING_ITEM, MODE_DRAGGING_HOLE, MODE_FITTING_IMAGE, MODE_UPLOADING_IMAGE,
  MODE_ROTATING_ITEM, CAMERA_TYPE
} from '../../constants';
import * as SharedStyle from '../../shared-style';
import {MdSearch, MdCheck, MdSelectAll, MdCamera, MdPlace, MdFileUpload, MdAdd, MdEdit, MdGroup, MdChildCare, MdFolder, MdChildFriendly} from 'react-icons/md';
import {Seq} from 'immutable';

const VISIBILITY_MODE = {
  MODE_IDLE, MODE_2D_ZOOM_IN, MODE_2D_ZOOM_OUT, MODE_2D_PAN, MODE_3D_VIEW, MODE_3D_FIRST_PERSON,
  MODE_WAITING_DRAWING_LINE, MODE_DRAWING_LINE, MODE_DRAWING_HOLE, MODE_DRAWING_ITEM, MODE_DRAGGING_LINE,
  MODE_DRAGGING_VERTEX, MODE_DRAGGING_ITEM, MODE_DRAGGING_HOLE, MODE_FITTING_IMAGE, MODE_UPLOADING_IMAGE,
  MODE_ROTATING_ITEM
};

const contentArea = {
  padding: '0.25em 1.15em',
  cursor: 'pointer',
  marginBottom: '1em',
  userSelect: 'none'
};

const filterArea = {
  
  height: 'auto',
  overflowY: 'auto',
  maxHeight: "21em",
  marginTop: '1em'

}

const elementStyle = {
  width: 'auto',
  height: '2.5em',
  margin: '0.25em 0.25em 0 0',
  padding: '0.5em',
  textAlign: 'center',
  display: 'inline-block',
  border: '1px solid #CCC',
  borderRadius: '0.2em'
};

const chooseCamera = {
  width: '80%',
  padding: 3,
  borderRadius: 3
}

const activeAssociate = { float: 'right', marginTop: 12, padding: '6px 12px',  background: '#6F8E71',   border: 'none',   color: 'white'}
const deactiveAssociate = { float: 'right', marginTop: 12, padding: '6px 12px',  background: 'gray',   border: 'none',   color: 'white'}
const tableSearchStyle = {width: '100%', marginTop: '0.8em'};
const searchIconStyle = {fontSize: '1.5em'};
const searchInputStyle = {fontSize: '1em', width: '100%', height: '1em', padding: '1em 0.5em'};
const imgStyle = {width: 36, height: 36, borderRadius: 3}

export default class PanelFilters extends Component {

  constructor(props, context) {
    super(props, context);

    this.state = {
      elements: [],
      matchString: '',
      matchedElements: [],
      associate: false,
      categories: [],
      things: [],
      selCat: -1,
      selThing: -1
    };


  }

  componentDidMount(){

    console.log("context loaded : ", this.props)  
    fetch('https://dev.api.artishok.io/reactor/admin/thing/categories')
    .then(response => response.json())
    .then(data =>{
      console.log("api data : ", data)
      this.setState({categories: data})    
    })
    .catch(err=>{
      console.log("api get error : ", err)
    })
    
  }


  tryAssociate(layer, element, e){

    let {associate, selCat, selThing, categories, things} = this.state
    let {state} = this.props
    let {sceneActions} = this.context

    console.log("associate toggle : " , associate, selCat, selThing, layer.get("items"), element.get("associated"))
    if(selThing < 0 || selCat < 0) {alert("please select category and things for associate.");  return;}

    let newElement = new Map(element)
    let items = layer.get("items")
    items = new Map(items)
    newElement.set("associated", selThing)
    console.log("updated element : ", newElement, selThing, items)
    items.set(element.get("id"), newElement)

    // items.get(element.get("id")).set(element)
    // sceneActions.setLayerProperties(layer.get("id"), {items})
    // this.setState({associate:  !associate})
    // let url = `https://dev.api.artishok.io/reactor/admin/thing/${things[selThing].id}/floor/${things[selThing].floor_id}`
    // console.log("url : ", url)
    // let method = "get"

    // if(this.state.associate)
    //   method = "get"
    // else
    //   method= "delete"
    // fetch('https://dev.api.artishok.io/reactor/admin/thing/search', {
    //   method: method
    // })
    // .then(response => response.json())
    // .then(data =>{
    //   console.log("api asseociate response: ", data);
    
    // })
    // .catch(err=>{
    //   console.log("api asseociate error : ", err)
    // })

  }




  // loadFloorPlanFromFile(event){
  //   let {projectActions} = this.context
  //   event.preventDefault();
  //   browserUpload().then((data) => {
  //     console.log("floor plan file : ", data)
  //     // projectActions.loadProject(JSON.parse(data));
  //   });
  // }
  componentWillReceiveProps(nextProps) {
    if (this.state.matchString !== '') {
      this.setState({
        matchedElements: {
        }
      });
    } else {
      this.setState({elements:[], matchedElements: []});
    }
  }

  selCamera(e){
    let {projectActions} = this.context    
    projectActions.setCamera(e.target.value)
  }
  
  selCat(e){
    this.setState({selCat: e.target.value})

    fetch('https://dev.api.artishok.io/reactor/admin/thing/search', {
      method: 'post',
      body: JSON.stringify({"options":{
          "size":50,
          "page":"0"
          },type: "Camera"})
    })
    .then(response => response.json())
    .then(data =>{
      console.log("api things data : ", data);
      this.setState({things: data})
    
    })
    .catch(err=>{
      console.log("api call error : ", err)
    })


  }
  selThing(e){
    this.setState({selThing: e.target.value})
  }

  render() {

    let {state} = this.props
    let {translator} = this.context
    let {associate} = this.state

    let componentRenderer = (element, layer) =>
    <Panel key={element.id}  name={'Artishok Controls'} opened={true}>
      <div style={contentArea}>          

          <table style={tableSearchStyle}>
            
            <thead>
              <tr>
                <td></td>
                <td style={{fontSize: 14, color: 'lightgreen', paddingBottom: 12}}>Things</td>
                <td></td>
              </tr>
            </thead>

            <tbody>

              <tr>
                <td style={{width: '10%'}}><MdFolder style={searchIconStyle}/></td>
                <td><select style={chooseCamera} onChange={this.selCat.bind(this)}>
                  <option value={-1} key={-1} >Category</option>               
                 {  this.state.categories.map((item, index)=>{
                   return (<option value={index} key={index} >{item}</option>)
                 })
                 }
                  </select>
                  </td>
              </tr>      

              <tr>
                <td style={{width: '10%'}}><MdChildFriendly style={searchIconStyle}/></td>
                <td>
                   <select style={chooseCamera} onChange={this.selThing.bind(this)} value={element.associate} >
                  <option value={-1} key={-1} >Thing</option>               
                 {  this.state.things.map((item, index)=>{
                   return (<option value={item.id} key={index} >{item.name}</option>)
                 })
                 }
                  </select> 
                </td>
              </tr>         

              <tr>
                <td></td>
                <td> 
                  <div style={{width: '80%'}}>
                    <button style={associate? deactiveAssociate:activeAssociate} onClick={this.tryAssociate.bind(this, layer, element)}>
                    {associate? "Deassociate":"Associate"}
                    </button>
                  </div>
                </td>
              </tr>    

            </tbody>
          </table>


        </div>
    </Panel>;

    let layerRenderer = layer => Seq()
      .concat(layer.lines, layer.holes, layer.areas, layer.items)
      .filter(element => element.selected)
      .map(element => componentRenderer(element, layer))
      .valueSeq();
  return <div>{state.scene.layers.valueSeq().map(layerRenderer)}</div>

  }
}

PanelFilters.propTypes = {
  state: PropTypes.object.isRequired,

};

PanelFilters.contextTypes = {
  catalog: PropTypes.object.isRequired,
  translator: PropTypes.object.isRequired,
  itemsActions: PropTypes.object.isRequired,
  linesActions: PropTypes.object.isRequired,
  holesActions: PropTypes.object.isRequired,
  projectActions: PropTypes.object.isRequired,
  translator: PropTypes.object.isRequired,
  sceneActions: PropTypes.object.isRequired
};
