import React, { Component } from 'react';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import Constants from '../../helper/Constants.jsx';
import store from '../../store.jsx'
import { onSaveCollection,onChangeRoute } from '../../actionCreators.jsx';
import {
  getSchemas
} from '../../services/index.jsx';

const customContentStyle = {
  width: '400px',
  maxWidth: 'none',
};
const styles = {
  customWidth: {
    width: 150,
  },
};
class FormNewCollection  extends Component {
	constructor(props) {
	    super(props);
	    this.state = {
	        open: false,
	        name:"",
	        lang:"",
	        config:"{}",
	        errorName:""
        };
        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handleSave = this.handleSave.bind(this);
  	}
  	handleOpen(){
  	  this.setState({open: true});
  	};

  	handleClose(){
  	  this.setState({open: false});
      this.props.onClose();
  	};
  	handleChange = (event) => {
	    this.setState({
	      name: event.target.value,
	    });
 	};
  	componentWillReceiveProps(props) {
  	  this.setState({
  	  	"open":props.open
  	  });
  	}
  	handleSave(){
  		var me = this;
  		let collection = {
  			"name":this.state.name,
  			"lang":this.state.lang,
  			"config":"{}"
  		};

      getSchemas({"name":collection.name})
      .then( response => {
        let {data} = response;
        let result = data.data;
        
        if(result.length>0){
          me.setState({
            errorName:"Ya existe una coleccion con este nombre."
          });
          return;
        }
        
        store.dispatch(onChangeRoute());
        store.dispatch(onChangeRoute({text:"Collections",link:"/"}));
        store.dispatch(onChangeRoute({text:collection.name,link:"/database/"+collection.name}));

        if(me.props.onSave){
          me.props.onSave(collection);
        }
        
      })
      .catch(err => console.log("ERROR: ",err.message));
  		return;
      fetch(Constants.URL_SCHEMA, {
  		    method: 'POST',
  		    headers: {
  		      'Accept': 'application/json, text/plain, */*',
  		      'Content-Type': 'application/json',
  		      'token':store.getState().token
  		    },
  		    body:JSON.stringify(collection),
  		}).then(function(response) {
  		    if (response.status >= 400) {
  		      throw new Error("Bad response from server");
  		    }
  		    return response.json();
  		}).then(function(response) {
  		      console.log(response);  
  		      if(response.success){
              collection["_id"] = response._id;
  		        me.props.onSave(collection);
  		      }else{
  		      	me.setState({
  		      		errorName:(typeof response.msg === 'object')?response.msg.errmsg:response.msg
  		      	});
  		      }
  		}).catch(function(err) {
  		    console.log(err)
  		});
  	}
  	render(){
  		const actions = [
	      <FlatButton
	        label="Cancelar"
	        primary={true}
	        onClick={this.handleClose}/>,
	      <FlatButton
	        label="Aceptar"
	        primary={true}
	        onClick={this.handleSave} />
  		];
  		return(
			<Dialog
				  	className="win"
				  	title="Crear Nuevo"
				  	modal={true}
				  	actions={actions}
				  	open={this.state.open}
				  	contentStyle={customContentStyle}
				  	>
	  			<Container>	
	  				<Row>
	  			 	<TextField
	  			 	       className="form-field"	
		  			       errorText={this.state.errorName}
		  			       floatingLabelText="Nombre"
		  			       name="name"
		  			       onChange={this.handleChange} 
		  			       value={this.state.name}/>
	  			  	<SelectField
  			         	menuItemStyle={{color:"#000"}}
  			  	     	className="form-field"	
			            floatingLabelText="Lenguaje"
  			            value={this.state.lang}
  			            onChange={(event, index, value) => this.setState({"lang":value})}>
	  			            <MenuItem value="es" primaryText="Español" />
	  			            <MenuItem value="en" primaryText="Ingles" />
		            </SelectField>
		  			</Row>
	  			</Container>
			</Dialog>
		);
  	}

}
export default FormNewCollection;