import React ,{ PureComponent } from 'react';
import { Col, Container, Row,Button,ButtonToolbar,Breadcrumb,
  BreadcrumbItem,
  Card,
  CardBody,
  CardHeader,
  CardTitle,FormGroup
  } from 'reactstrap';
import { Link } from "react-router-dom";
import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";
import * as myConstClass from '../../constant.js';
import $ from 'jquery';
import { ValidatorForm, TextValidator } from 'react-material-ui-form-validator';
import { toastr } from "react-redux-toastr";

class Add extends PureComponent {

  constructor(props) {//alert('in..');
    super(props);
    this.state = {
      
      user_id:'',
      posts: [],
      branch:[],
      codes:[],
      formData: {
        sapcode: '',
        firstname: '',
        middlename: '',
        lastname: '',
        email:'',
        

    },
    submitted: false,
    }
    //this.handleSubmit = this.handleSubmit.bind(this);
  }
  componentDidMount(){
   
    const answer_array = this.props.location.pathname.split('/');
    //alert(answer_array['3']);
    if(answer_array['3']){
      
      this.state.user_id = answer_array['3'];
      fetch(myConstClass.BASE_URL+'/user/getUpdateUserInfo/'+answer_array['3'])
  .then(response => response.json())
  .then(response =>{this.setState({formData: response})}).catch(err => console.log(err))
      
    }else{
      this.state.user_id = '';
    }

    
  if(!localStorage.getItem('session_id')){
    console.log('History:',this.props);      
    this.props.history.push('/');
  }

  }
  handleChange = (event) => {//alert('2');
    const { formData } = this.state;
    formData[event.target.name] = event.target.value;
    this.setState({ formData });
}




handleSubmit = () => {
 
  this.setState({ submitted: true }, () => {
    
      setTimeout(() => this.setState({ submitted: false }), 5000);
      fetch(myConstClass.BASE_URL+`/user/add/`+this.state.user_id, {
              method: 'POST',
              body: JSON.stringify($('#pform').serializeArray()),
            }).then(response =>  response.json()).then((response) => {
              if(response == true){
               // toast('User Added Successfully..!', {containerId: 'B',type: toast.TYPE.SUCCESS})
                this.props.history.push('/forms/users/');
              }else{
               // toast('User Insertion Failed..!', {containerId: 'B',type: toast.TYPE.ERROR})
              }
            })
            .catch();
  });
}


  render() {
    const { formData, submitted,branch,codes } = this.state;
    const { posts} = this.state;
    return (
      <Container fluid>
    <Header>
      <HeaderTitle>Measures</HeaderTitle>

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        {/* <BreadcrumbItem>
          <Link to="/dashboard">measures</Link>
        </BreadcrumbItem> */}
        <BreadcrumbItem active>Add</BreadcrumbItem>
      </Breadcrumb>
    </Header>
    <Card>
      {/* <Row>
      <Col md={12}>
      {this.state.user_id ? <h3 className="page-title">Edit Employees</h3> : <h3 className="page-title">Add Employees</h3>}
        
        {/* <h3 className="page-subhead subhead">Use this elements, if you want to show some hints or additional
              information
        </h3> */}
      {/* </Col>
    </Row> */} 
     <CardBody>
   
        <ValidatorForm
                className="material-form" id="pform" 
                onSubmit={this.handleSubmit}
            >      
     
          <Row>
          <Col lg="6">
              <FormGroup>            
            <TextValidator
             onChange={this.handleChange}
             name="sapcode"          
             label="SAP Code"
             value={formData.sapcode}
             validators={['required','matchRegexp:^[0-9]+$']}
             errorMessages={['this field is required','Enter Number..']}
             className="material-form__field"
            />            
         </FormGroup>
            <TextValidator
            onChange={this.handleChange}
              name="firstname"
              placeholder="First name"
              label="First name"
              className="material-form__field"
              value={formData.firstname}
             validators={['required']}
             errorMessages={['this field is required']}
            />
             <br/>
            <TextValidator
            onChange={this.handleChange}
            className="material-form__field"
              name="middlename"
              placeholder="Middle name"
              label="Middle name"
              value={formData.middlename}
             validators={['required']}
             errorMessages={['this field is required']}
            />
             <br/>
            <TextValidator
            onChange={this.handleChange}
            className="material-form__field"
              name="lastname"
              placeholder="Last name"
              label="Last name"
              value={formData.lastname}
             validators={['required']}
             errorMessages={['this field is required']}
            />
          </Col>
         
          <Col md={6} lg={6}>
          <TextValidator
            onChange={this.handleChange}
            className="material-form__field"
              name="designation"
              placeholder="Designation"
              label="Designation"
              value={formData.designation}
             validators={['required']}
             errorMessages={['this field is required']}
            />
          <br/>
            <TextValidator
            onChange={this.handleChange}
            className="material-form__field"
              name="department"
              placeholder="Department"
              label="Department"
              value={formData.department}
             validators={['required']}
             errorMessages={['this field is required']}
            />
         
          </Col>
          </Row>
          <br/>
          
              
          <Button
                    color="primary"
                    variant="contained"
                    type="submit"
                    disabled={submitted}
                >
                    {
                        (submitted && 'Your form is submitted!')
                        || (!submitted && 'Submit')
                    }
                </Button>
               
          </ValidatorForm>
          
    
 

  
    </CardBody>
    </Card>
    
    
  </Container>
    )

  }

}



export default Add;
