import React,{ PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import DatePicker from "react-datepicker";
import dateFormat from 'dateformat';
import {
  Breadcrumb,
  BreadcrumbItem, Button,Row,Label,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container, Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
} from "reactstrap";
import TimePicker from 'react-time-picker';
import "react-datepicker/dist/react-datepicker.css";
import './datepicker.scss';
import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";

import BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
import  { Redirect } from 'react-router-dom' 
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox
} from "availity-reactstrap-validation";
import swal from 'sweetalert';
const tableColumns = [
  {
    dataField: "admin_name",
    text: "User",
    sort: true,
    headerStyle: { width:"10%" }
  },
  {
    dataField: "user_ip",
    text: "User IP ",
    sort: true,
    headerStyle: { width:"8%" }
  },
  {
    dataField: "location",
    text: "Location",
    sort: true,
    headerStyle: { width:"10%" }
  },
  {
    dataField: "operation",
    text: "Operation",
    sort: true,
    headerStyle: { width:"10%" }
    
  },
  {
    dataField: "affected_table",
    text: "Affected Table",
    headerStyle: { width:"10%" }
  },
  {
    dataField: "rows",
    text: "Rows",
    headerStyle: { width:"7%" }
  },
  {
    dataField: "timestamp",
    text: "Timestamp",
    headerStyle: { width:"10%" }
  },
  
];

class Logs extends PureComponent {
    constructor(props) {
      super(props);
      this.routeChange = this.routeChange.bind(this);
      //this.googleTranslateElementInit = this.googleTranslateElementInit.bind(this);
      this.search = this.search.bind(this);
      this.state = {
        user_id:0,
        from_date:Date.now(),
        to_date:Date.now(),
        formData:'',
        emp:'',
        posts:'',
        timeOut: 5000,
        showCloseButton: true,
        progressBar: true,
        position: "top-right"
      }

    //   submitted: false,
    }
 
    routeChange() {
      this.props.history.push('/');
    }
    

      handleFromDateChange = (from_date) => {  
        this.setState({ from_date });
        var admin_id= localStorage.getItem('uname'); 
        var fdate = dateFormat(from_date,'yyyy-mm-dd');
        var tdate = dateFormat(this.state.to_date,'yyyy-mm-dd');
       
        fetch(myConstClass.BASE_URL+'user/getLogs/'+admin_id+'/'+fdate+'/'+tdate)
        .then(response => response.json())
        .then(response =>{
          let i=1;  
        response.forEach(element => {
          let id=element.id;
        element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(id)} /><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} /><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;
         // console.log(element);
         element.id = i;
         i++;
        });
        this.setState({formData: response})
      }).catch(err => console.log(err))
        var from = { from_date };
      };
  
      handleToDateChange = (to_date) => { 
        this.setState({to_date });
        var admin_id= localStorage.getItem('uname'); 
        var fdate = dateFormat(this.state.from_date,'yyyy-mm-dd');
        var tdate = dateFormat(to_date,'yyyy-mm-dd');
        fetch(myConstClass.BASE_URL+'user/getLogs/'+admin_id+'/'+fdate+'/'+tdate)
        .then(response => response.json())
        .then(response =>{
          let i=1;  
        response.forEach(element => {
          let id=element.id;
        element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(id)} /><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} /><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;
         // console.log(element);
         element.id = i;
         i++;
        });
        this.setState({formData: response})
      }).catch(err => console.log(err))
        var to = {to_date };
      };

      search(event){
        var admin_id= localStorage.getItem('uname'); 
        var fdate = dateFormat(this.state.from_date,'yyyy-mm-dd');
        var tdate = dateFormat(this.state.to_date,'yyyy-mm-dd');
        this.sid = event.target.value;
        if(admin_id == null){
          this.routeChange();
        } 
        fetch(myConstClass.BASE_URL+'user/getLogsOnSearch/'+admin_id+'/'+fdate+'/'+tdate+'/'+this.sid)
        .then(response => response.json())
        .then(response =>{
          let i=1;  
        response.forEach(element => {
          let id=element.id;
        // element.action = <div><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} /><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;
         // console.log(element);
         element.id = i;
         i++;
        });
        this.setState({formData: response})
      }).catch(err => console.log(err))        
      }
      componentDidMount() {

    //     window.googleTranslateElementInit = this.googleTranslateElementInit
    //     const google = window.google;
    // const script = document.createElement("script");
    // script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);  

        var admin_id= localStorage.getItem('uname'); 
        var fdate = dateFormat(this.state.from_date,'yyyy-mm-dd');
        var tdate = dateFormat(this.state.to_date,'yyyy-mm-dd');
        if(admin_id == null){
          this.routeChange();
        } 
        fetch(myConstClass.BASE_URL+'user/getLogs/'+admin_id+'/'+fdate+'/'+tdate)
        .then(response => response.json())
        .then(response =>{
          let i=1;  
        response.forEach(element => {
          let id=element.id;
        // element.action = <div><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} /><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;
         // console.log(element);
         element.id = i;
         i++;
        });
        this.setState({formData: response})
      }).catch(err => console.log(err))          
      }

      // googleTranslateElementInit () {
      //   /* eslint-disable no-new */
      //   const google = window.google;
      //     new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
      //   new window.google.translate.TranslateElement({pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element')
      // }



      render() { 
        var admin_id= localStorage.getItem('uname'); 
        const { formData} = this.state;
        const { org} = this.state; 
          return(
        <Container fluid>
          <Header><div  id="google_translate_element"></div><br/>
            <HeaderTitle>System Logs</HeaderTitle>
      
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              {/* <BreadcrumbItem>
                <Link to="/dashboard">measures</Link>
              </BreadcrumbItem> */}
              <BreadcrumbItem active>System Logs</BreadcrumbItem>
              {/* <button class="mr-1 mb-1 btn btn-outline-secondary" onClick={() =>this.edit(this.state.user_id)} style={{color:'#ffffff',border: '1px solid #ffffff',float:'right !important',margin:'auto'}}><Icon.PlusCircle />&nbsp;&nbsp;ADD</button>
            */}
            </Breadcrumb>
            {/* <span >ADD</span> */}
            
          </Header>
          <Card>
          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV
          >
              {props => (
                <div>
                  <CardHeader>
                    <div className="float-right pull-right">
                    
                      {/* <MyExportCSV {...props.csvProps} /> */}
                    </div><br/>
                    {/* <CardTitle tag="h5">Export CSV</CardTitle>
                    <h6 className="card-subtitle text-muted">
                      Exportable CSV by react-bootstrap-table2
                    </h6> */}
                  </CardHeader>
                  <CardBody>
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
               
               {/* With AvGroup AvInput and AvFeedback to build your own */}
               <Row>
             
             
           <div class="col-md-3">
                <Label for="example">From Date </Label> <br/>
              <DatePicker
                name="from_date"
                selected= {this.state.from_date}
                onChange={this.handleFromDateChange}                
                dateFormat="dd-MM-yyyy"
                className="re_date_filter"
                value={this.state.from_date}
                /> 
                </div>
           
                <div class="col-md-3">
                {/* <AvGroup> */}
                <Label for="example" className="date_label">To Date </Label> <br/>
              <DatePicker
                name="to_date"
                selected= {this.state.to_date}
                onChange={this.handleToDateChange}                
                dateFormat="dd-MM-yyyy"
                className="re_to_date_filter"
                value={this.state.to_date}
                /> 
                </div>
           </Row>
           <Row>
           <div class="col-md-4"></div>
             <div class="col-md-4"></div>
           
              <div class="col-md-4">
               <Label for="example" className="search_title">Search</Label>
                <AvGroup>
              
                  <AvInput name="search" className="search" onChange={this.search} type="text" id="example"/>
                </AvGroup>
              </div>
            </Row>
            
           </AvForm><br/>
         
                    <BootstrapTable
                      {...props.baseProps}
                      bootstrap4
                      bordered={false}
                      pagination={paginationFactory({
                        sizePerPage: 25,
                        sizePerPageList: [5, 10, 25, 50]
                      })}
                    />
                  </CardBody>
                </div>
              )}
            </ToolkitProvider>
          </Card>
          
          {/* <ExportCSVTable /> */} 
        </Container>
          );
      }

}

export default Logs;