import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as SharedStyle from '../../shared-style';
import { MdEdit, MdExitToApp, MdClose, MdCamera } from 'react-icons/md';
import Modal from 'react-modal';
import { projectActions } from '../../actions/export';
import { CAMERA_TYPE } from '../../constants';
import { Project } from '../../class/export';
const TopBarStyle = {
  position: 'absolute',
  top: 0,
  lineHeight: '14px',
  fontSize: '12px',
  color: SharedStyle.COLORS.white,
  backgroundColor: "#6F8E71",
  padding: '3px 1em',
  margin: 0,
  boxSizing: 'border-box',
  cursor: 'default',
  userSelect: 'none',
  zIndex: '9001',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center'
};

export const leftTextStyle = {
  position: 'relative',
  float: 'left',
  padding: '0 1em',
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  height: '100%'

};

export const rightTextStyle = {
  position: 'relative',
  borderLeft: '1px solid #FFF',
  float: 'right',
  padding: '0 1em',
  display: 'inline-block'
};

const coordStyle = {
  display: 'inline-block',
  margin: 0,
  padding: 0,
  marginLeft : 12
};

const customStyles = {
  content : {
    top: '24%',
    minWidth: 360,
    width: '45%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)',
    padding: 0
  },
  overlay: {
    backgroundColor: 'rgba(221, 221, 221, 0.75)'
  }
};

const modalHeader = {
  padding: 12,
  display: 'flex',
  justifyContent: 'space-between',
  borderBottom: '2px solid lightgray'
}
const inputItem = {
  margin: 5,
  display: 'flex',
  alignItems: 'center'

}

const modalContent = {
  borderBottom: '2px solid lightgray',
  padding: 18, paddingBottom: 54

}
const modalFooter = {
  padding: 12,
  display: 'flex',
  justifyContent: 'flex-end',
  alignItems: 'center'
}


const chooseCamera = {
  width: 124,
  padding: 3,
  borderRadius: 3
}

const buttonItem = {
  padding: '6px 15px',
  border: 'none',
  color: 'white',
  marginRight: 10,
  borderRadius: 3
}
const tableSearchStyle = {width: '100%'};
const searchIconStyle = {fontSize: '1.5em'};

Modal.setAppElement('#app')


export default class TopBar extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {modalIsOpen: false, location: '', floorplan: '', ifNew: false, isFirst: true, btnEnable: false};
    this.checkSavedOrNot.bind(this)
  }

  componentDidMount(){
    let {state} = this.props

  }

  componentDidUpdate(){

    let {state} = this.props
    let {location, floorplan} = this.state

    if(((location !=  state.get("location"))||(floorplan != state.get("floor"))) && this.state.isFirst){
      this.setState({location: state.get("location"), floorplan: state.get("floor"),  isFirst: false})
      this.checkSavedOrNot(state.get("floor"), this)      
    }

  }


  openEditLocation(){    
    console.log("Eidt location")
    this.setState({modalIsOpen: true})
  }

  closeModal(){
    this.setState({modalIsOpen: false})
  }


  updateValues(key, e){

    let state =  this.state
    state[key] = e.target.value
    this.setState(state)

    if(key=="floorplan" && state[key].length==36){
      this.checkSavedOrNot(state[key], this)
    }else{
      this.setState({btnEnable: false})
    }

  }


  checkSavedOrNot(floor_id, that, loadData){
    let { projectActions } = this.context;

    this.setState({ifNew: false, btnEnable: true})

    fetch(`https://dev.api.artishok.io/reactor/admin/floor/${floor_id}`)
    .then(response => response.json())
    .then(data =>{
      if(data.id){
        that.setState({ifNew: true})
        if(loadData){
          that.saveLocationFloor()

          console.log("respone : data : ", data)
          projectActions.loadProject(data["metadata"])

        }
      }
    })
    .catch(err=>{
      console.log("api get error : ", err)
    })
  }

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

  saveLocationFloor(e){    

    let {projectActions} = this.context
    projectActions.setLocation(this.state.location)
    projectActions.setFloor(this.state.floorplan)
    this.setState({modalIsOpen: false})

    if(e)
      e.preventDefault()
  }

  createFloor(){
    console.log("create floor : ")
    
    let {state} = this.props
    let {floorplan, location} = this.state

    state = Project.unselectAll( state ).updatedState;
    let saveData = state.get('scene').toJS()
    saveData.floor = floorplan
    saveData.location = location
    let that= this

    let data = {
      "name": "Create Floor Plan",
      "id": "2b342079-4ad6-40c5-a967-c5d04affcc51",
      "description": "First floor, reception, accountant and HR",
      "metadata": {
          
      },
      "location_id": "3815d31f-954e-42df-8f9e-42a56541f9a0"
    }

    data.id = floorplan
    data.metadata = saveData

    fetch('https://dev.api.artishok.io/reactor/admin/floor', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data =>{
      console.log("respone : data : ", data)
      that.saveLocationFloor()    
      that.setState({ifNew: true})
    })
    .catch(err=>{
      console.log("api call error : ", err)
    })

  }

  updateFloor(){

    let {state} = this.props
    let {floorplan, location} = this.state
    let { projectActions } = this.context;

    state = Project.unselectAll( state ).updatedState;
    let saveData = state.get('scene').toJS()
    saveData.floor = floorplan
    saveData.location = location
    let that= this

    let data = {
      "name": "Update Floor Plan",
      "id": "2b342079-4ad6-40c5-a967-c5d04affcc51",
      "description": "First floor, reception, accountant and HR",
      "metadata": {
          
      },
      "location_id": "3815d31f-954e-42df-8f9e-42a56541f9a0"
    }

    data.id = floorplan
    data.metadata = saveData

    fetch('https://dev.api.artishok.io/reactor/admin/floor/2b342079-4ad6-40c5-a967-c5d04affcc51', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data =>{
      console.log("respone : data : ", data)
      that.saveLocationFloor()    
    })
    .catch(err=>{
      console.log("api call error : ", err)
    })
  }

  loadFloor(){
    console.log("load floor")
    this.checkSavedOrNot(this.state.floorplan, this, true)
  }


  render() {
    let { state: globalState, width, height } = this.props;
 
    return (
      <div style={{ ...TopBarStyle, width, height }}>
          <div style={leftTextStyle}>
            <div title={'Location ID'} style={coordStyle}>Location : {this.state.location}</div>
            <div title={'Floor ID'} style={coordStyle}>Floor : {this.state.floorplan}</div>
            <MdEdit style={coordStyle, {fontSize: 15, marginLeft: 16, cursor: 'pointer'}} onClick={this.openEditLocation.bind(this)} />
          </div>

          <div>
            <table style={tableSearchStyle}>
              <tbody>
                <tr>
                  <td style={{width: 24}}><MdCamera style={searchIconStyle}/></td>
                  <td ><select style={chooseCamera} onChange={this.selCamera.bind(this)} value={globalState.get("camera")} >
                
                  {  CAMERA_TYPE.map((item, index)=>{
                    return (<option value={item} key={index} >{item}</option>)
                  })
                  }
                    </select>
                    </td>
                </tr>
              </tbody>
            </table>
          </div>

          <Modal
            isOpen={this.state.modalIsOpen}
            onRequestClose={this.closeModal.bind(this)}
            style={customStyles}
            contentLabel="Example Modal"
          >
            <div>              
              <div style={modalHeader}>
                <label>Location and Floor Plan</label>
                <label onClick={this.closeModal.bind(this)}><MdClose/></label>
              </div>
              <div style={modalContent}>
                <div style={inputItem}>
                  <label style={{width: "30%"}}>
                    Location ID : 
                  </label>
                  <input type="text" style={{margin: 1, width: '42%',  border: '2px solid grey', height: 30, borderRadius: 5}} value={this.state.location} onChange={this.updateValues.bind(this, 'location')} />
                </div>
                <br></br>
                <div style={inputItem}>
                  <label style={{width: "30%"}}>
                    FloorPlan ID : 
                  </label>
                  <input type="text" style={{margin: 1, width: '42%',  border: '2px solid grey', height: 30, borderRadius: 5}} value={this.state.floorplan}  onChange={this.updateValues.bind(this, 'floorplan')} />
                </div>
              </div>

              <div style={modalFooter}>     

                {(this.state.ifNew && <button style={{...buttonItem, background: 'orangered'}} disabled={!this.state.btnEnable} onClick={this.loadFloor.bind(this)}>Load & Clear</button>)}           
                
                {this.state.ifNew? <button style={{...buttonItem, background: '#6F8E71'}} disabled={!this.state.btnEnable}  onClick={this.updateFloor.bind(this)}>Update</button> : <button style={{...buttonItem, background: 'steelblue'}} disabled={!this.state.btnEnable}  onClick={this.createFloor.bind(this)}>Create</button>}
                <button style={{...buttonItem, background: 'grey'}} onClick={this.closeModal.bind(this)}>
                  Cancel
                </button>
              </div>
              
            </div>
          
          </Modal>


      </div>
    );
  }
}

TopBar.propTypes = {
  state: PropTypes.object.isRequired,
  footerbarComponents: PropTypes.array.isRequired,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
  softwareSignature: PropTypes.string
};

TopBar.contextTypes = {
  projectActions: PropTypes.object.isRequired,
  viewer2DActions: PropTypes.object.isRequired,
  viewer3DActions: PropTypes.object.isRequired,
  linesActions: PropTypes.object.isRequired,
  holesActions: PropTypes.object.isRequired,
  itemsActions: PropTypes.object.isRequired,
  translator: PropTypes.object.isRequired,
};
