import React, {Component} from 'react';
import PropTypes, { object } from 'prop-types';
import { FormLabel, FormColorInput } from '../../components/style/export';
import PropertyStyle from './shared-property-style';
import { MdFolder, MdChildFriendly } from 'react-icons/md';


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 searchIconStyle = {fontSize: '1.5em'}


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


export default class PropertyAssociated extends Component{
  constructor(props){
    super(props)
    this.state = {
      elements: [],
      matchString: '',
      matchedElements: [],
      associate: false,
      categories: [],
      things: [],
      selCat: "",
      selThing: ""
    }

    this.selectCategory = this.selectCategory.bind(this)
  }  

  componentDidMount(){
    let{value} = this.props
    let that = this

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

    if(value.get("category")!="-"){
      that.selectCategory(value.get("category"), that)
    }

    if(value.get("thing")!="-")
      that.setState({selThing: value.get("thing")})

  }

  
  selCat(e){
      this.selectCategory(e.target.value)
  }

  selectCategory(category, that){

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

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

  tryAssociate(){
    let {selCat, selThing} = this.state
    let{value, onUpdate} = this.props
    if(selThing < 0) {alert("please select category and things for associate.");  return;}
    let thingName = "", popUp= "", hoverColor = ""
    this.state.things.map(item=>{
      if(item.id == selThing) {
        thingName = item.name   
        popUp = item['popup']
        hoverColor = item['color']
      }
    })
    let merged = (value.get("thing")==selThing)? value.merge({ category: "-", thing: "-", thingName: "", popUp: "", hoverColor: "#ffffff"}) :value.merge({ category: selCat, thing: selThing, thingName, popUp, hoverColor})   
    return onUpdate(merged)
  }


  render(){

    let{value, configs} = this.props
    let {selCat, selThing} = this.state
    let category = ""
    let thing = ""
    category = value.get("category")
    thing = value.get("thing")
    

    return (
      <table className="PropertyColor" style={PropertyStyle.tableStyle, {marginTop: 12, width: '100%'}}>              
        <thead>
          <tr>
            <td></td>
              <td style={{fontSize: 14, color: 'lightgreen', paddingBottom: 12}}>{configs.label}</td>
            <td></td>
          </tr>
        </thead>
          <tbody>
          <tr>
            <td style={{width: '10%'}}><MdFolder style={searchIconStyle}/></td>
            <td><select style={chooseCamera} onChange={this.selCat.bind(this)}  value={selCat}>
              <option value={-1} key={-1}  >Select Category</option>               
            {  this.state.categories.map((item, index)=>{
              return (<option value={item} key={index} disabled={(category==item) ? true:false}>{item}</option>)
            })
            }
              </select>
              </td>
          </tr>  
          <tr>
            <td style={{width: '10%'}}><MdChildFriendly style={searchIconStyle}/></td>
            <td>
              <select style={chooseCamera} onChange={this.selThing.bind(this)} value={selThing} >
              <option value={-1} key={-1} >Select Thing</option>               
            {  this.state.things.map((item, index)=>{
              return (<option value={item.id} key={index} disabled={thing==item.id?true:false} >{item.name}</option>)
            })
            }
              </select> 
            </td>
          </tr>        
          <tr>
            <td></td>
            <td> 
              <div style={{width: '80%'}}>
                <button style={thing==selThing? deactiveAssociate:activeAssociate} onClick={this.tryAssociate.bind(this)}>
                {thing==selThing? "Deassociate":"Associate"}
                </button>
              </div>
            </td>
          </tr>  
        </tbody>
  
      </table>
    );

  }
  
}

PropertyAssociated.propTypes = {
  value: PropTypes.any.isRequired,
  onUpdate: PropTypes.func.isRequired,
  configs: PropTypes.object.isRequired,
  sourceElement: PropTypes.object,
  internalState: PropTypes.object,
  state: PropTypes.object.isRequired
};
