import React, { Component } from 'react';
import Constants from "../../helper/Constants.jsx"

import {
  AppCode,
  Breadcrumb,
  AppCard
} from "../../components/index.jsx";



import Helper from "../../helper/Helper.jsx"
import Collection from './Collection.jsx';
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import Divider from 'material-ui/Divider';
import Snackbar from 'material-ui/Snackbar';
import AutoComplete from 'material-ui/AutoComplete';
import { onSaveCollection, onGetCollection, onMessage, getCollections, onlinkRoutes, onChangeRoute } from '../../actionCreators.jsx';
import store from '../../store.jsx';
import LinearProgress from 'material-ui/LinearProgress';
import {
  getSchemas,
  removeSchema
} from '../../services/index.jsx';

import FormNewCollection from './FormNewCollection.jsx';
import Dialog from 'material-ui/Dialog';
import { withRouter } from 'react-router';

class Database  extends Component {
	constructor(props) {
	    super(props);
	    this.state = {
        open: false,
        openMessage: false,
        message:"",
        loading:false,
        error:null,
        disabled:false,
        linkRoutes:[{ text:"Collections",link:"/database"}],
        expanded:false,
        openConfirm:false,
        collection:{},
        view:"list",
        schemas:[],
        _state:{},
        value:vkbeautify.json('{ "name":"String", "apellido":{"type":"String","required":"true"}}')
      };

      this.listarSchemas = this.listarSchemas.bind(this);
      this.handleNew = this.handleNew.bind(this);
      this.onClose = this.onClose.bind(this);
      this.handleOpen = this.handleOpen.bind(this);
      this.onSave = this.onSave.bind(this);
      this.handleSave = this.handleSave.bind(this);
      this.handleEditar = this.handleEditar.bind(this);
      this.handleRemove = this.handleRemove.bind(this);
      this.onRemove = this.onRemove.bind(this);
      this.enableButton = this.enableButton.bind(this);
      this.handleViewDocuments = this.handleViewDocuments.bind(this);
  	}

    handleOpen(){
      this.setState({open: true});
    };

    onClose(){
      this.setState({open: false});
    };
    componentWillMount() {

     let me = this;
     let props = this.props;
     let name = Helper.getHashParam(location.hash);
     let params = {};

     if(name!== 'database'){
        params["name"] = name;
        console.log("View Doc: ",name);
     }

     store.subscribe(() => {
      let _state = store.getState();
      if(typeof _state.collection !== "undefined"){
        this.setState({
          "collection":_state.collection
        });
      }
     });

     if(props){
       let match = props.match;
       name = match.params.name
       console.log("Name: ",name);
     }

      this.setState({loading:true});
      this.listarSchemas(params)
      .then( collection => {
        console.log("Listar Schemas.",collection);

        let {location:{state}} = me.props;
        console.log("View Database on Mount: ",state,location);

        if(state){
          let name = state.name;

          store.dispatch(onChangeRoute());
          store.dispatch(onChangeRoute({text:"Collections",link:"/"}));
          store.dispatch(onChangeRoute({text:collection.name,link:"/database/"+collection.name}));
          
          me.setState({
            collection,
            view:"edit"
          });
        }else{
          store.dispatch(onChangeRoute({text:"Collections",link:"/database"}));
        }
      }, err => {
        console.log("ERROR: ",err.message);
      });
    }

    listarSchemas(params){
      var me  = this;

      return new Promise((resolve,reject) => {
        //console.log("Listar Schemas!");
        getSchemas(params)
        .then(response => {
          let resp = response.data;

          me.setState({loading:false});
          
          if(!params.name){
            let schemas = [];  
            if(resp.data){
              schemas = resp.data;
            }
            me.setState({
              schemas
            });
          }else{
            let collection = resp.data[0];
            
            if(collection){
              store.dispatch(onChangeRoute());
              store.dispatch(onChangeRoute({"text":"Collections","link":"/database"}));
              store.dispatch(onChangeRoute({"text":collection.name,"link":"/collection/"+collection.name+"/"+collection.alias}));

              store.dispatch(onSaveCollection({
                "_id":collection._id,
                "name":collection.name,
                "state":collection.state,
                "status":collection.status,
                "lang":collection.lang,
                "config":collection.config
              }));
              me.setState({
                view:"edit",
                collection
              });
            }else{
              let {location:{state}} = me.props;
              if(state){
                collection = state.collection;
                
              }
            }
            resolve(collection);
          }
        })
        .catch(err => {
          //console.log("ERROR: ",err.message);
          reject(err);
        });
      });

    }
    handleNew(){
      this.setState({
        open:true
      });
    }
    onSave(collection){
      const { history, location } = this.props || [];
      store.dispatch(onSaveCollection(collection));




      history.push({
        pathname: '/database/'+collection.name,
        state:{
          collection,
          view:"edit"
        }
      });
      this.setState({
        open: false,
        view:"edit"
      });
    }

    handleEditar(item){
      
      store.dispatch(onChangeRoute());
      store.dispatch(onChangeRoute({text:"Collections",link:"/"}));
      store.dispatch(onChangeRoute({text:item.name,link:"/collection/"+item.name+"/"+item.alias}));

      console.log("Clikced: ",item);

      store.dispatch(onSaveCollection({
        "_id":item._id,
        "name":item.name,
        "state":item.state,
        "status":item.status,
        "lang":item.lang,
        "config":item.config
      }));
      this.setState({
        view:"edit",
        //linkRoutes:this.state.linkRoutes.concat({text:store.getState().collection.name,link:"/database/"+item.name})
      });
    }
    handleSave(){

      var me = this;
      let {collection} = this.state;

      console.log("SAVE!",collection);
      //let collection = this.state.collection;
      let {config} = collection;
      try{
        config = JSON.parse(config);
        if(Helper.isEmpty(config)){
          store.dispatch(onMessage({
              open:true,
              msg:"El Schema no puede estar vacio."
          }));
          return;
        }
      }catch(err){
        console.log("ERROR: ",err.message);
      }
      
      if(store.getState().error!=undefined){
        if(store.getState().error.message!=undefined){
          store.dispatch(onMessage({
              open:true,
              msg:store.getState().error.message
          }));
          return;
        }
      }
      let URL_SCHEMA = Constants.URL_SCHEMA+((collection._id)?"/"+collection._id:"");
      fetch(URL_SCHEMA, {
          method: (collection._id)?'PUT':'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){
              store.dispatch(onMessage({
                  open:true,
                  msg:response.msg
              }));

              getSchemas({"name":collection.name})
              .then(response => {
                let resp = response.data;
                if(resp.data.length>0){
                  let doc = resp.data[0];
                  if(doc){

                    store.dispatch(onChangeRoute());
                    store.dispatch(onChangeRoute({"text":"Collections","link":"/database"}));
                    store.dispatch(onChangeRoute({"text":doc.name,"link":"/collection/"+doc.name+"/"+doc.alias}));

                    store.dispatch(onSaveCollection({
                      "_id":doc._id,
                      "name":doc.name,
                      "state":doc.state,
                      "status":doc.status,
                      "lang":doc.lang,
                      "config":doc.config
                    }));
                    me.setState({
                      view:"edit",
                      collection:doc
                    });
                  }
                }
              })
              .catch(err => console.log("ERROR: ",err.message));
            }else{
              store.dispatch(onMessage({
                  open:true,
                  msg:response.msg
              }));
            }
      }).catch(function(err) {
          //console.log(err)
      });
    }
    handleRemove(_id){

      store.dispatch(onChangeRoute());
      store.dispatch(onChangeRoute({"text":"Collections","link":"/database"}));
      
      store.dispatch(onGetCollection(_id));
      
      this.setState({
        openConfirm:true
      });
    }
    enableButton(){
      return (this.state.error!=undefined);
    }
    handleViewDocuments(item){

        let {config} = item;

        store.dispatch(onChangeRoute());
        store.dispatch(onChangeRoute({"text":"Collections","link":"/database"}));

        if(config){
          config = JSON.parse(config);
          console.log("View Documents: ",Helper.isEmpty(config));
          if(Helper.isEmpty(config)){
            store.dispatch(onMessage({
                open:true,
                msg:"Debe definir el Schema para agregar Documentos a esta colección."
            }));
            return;
          }
        }

        const { history, location } = this.props || [];
        history.push({
          pathname: '/collection/'+item.name+'/'+item.alias,
          state:{
            collection:item,
            view:"list"
          }
        });
    }
    getView(){
      var self = this;
      switch(this.state.view){
        case "list":
          return(
          <div>
            {
              this.state.schemas.map((val,index) => {
                        let disabled = false;
                        if(val.config){
                          let config = JSON.parse(val.config);
                          disabled = (Helper.isEmpty(config));
                        }
                        return(
                          <AppCard 
                            className="code-item"
                            key={index}
                            title={val.name }
                            subtitle={val.slug}
                            state={val.state}
                            status={val.status}
                            actions={[
                              (!disabled && val.state !== "0")?
                              <IconButton tooltip="Ver Documentos" onClick={() => {this.handleViewDocuments(val)}} disabled={disabled}>
                                <FontIcon className="material-icons icon-tool">library_books</FontIcon>
                              </IconButton>:null,
                              <IconButton tooltip="Eliminar" onClick={() => {this.handleRemove(val._id)}}>
                                <FontIcon className="material-icons icon-tool">delete_forever</FontIcon>
                              </IconButton>,
                              <IconButton  tooltip="Editar" onClick={() => {this.handleEditar(val)}}>
                                <FontIcon className="material-icons icon-tool">mode_edit</FontIcon>
                              </IconButton>
                            ]}
                            >
                            <AppCode
                            readOnly={true}
                            config={val.config}
                            onChange={(val,editor) => {
                              try{
                                val = vkbeautify.json(val);
                                this.setState({
                                  "value":val
                                });
                              }catch(e){};
                            }} />
                          </AppCard>
                          )
              })
            }
          </div>);
        break;
        case "doc":
          return (
            <Collection collection={this.state.collection}/>
          );
        break;
        default:
          return(
              <AppCard 
                className="code-item code-edit" 
                iconStyle={{"backgroundColor":"red!important"}}
                title={<div><span><b>EDICIÓN: </b></span><span>{this.state.collection.name}</span></div>}
                subtitle={this.state.collection.slug}
                lang={this.state.collection.lang}
                expanded={true}
                editable={true}
                state={this.state.collection.state}
                status={this.state.collection.status}
                actions={[
                   <IconButton tooltip="Guardar" onClick={this.handleSave}>
                    <FontIcon className="material-icons icon-tool">save</FontIcon>
                  </IconButton>
                ]}
                >
                <AppCode
                readOnly={false}
                config={this.state.collection.config}/>
              </AppCard>
          )
        break;
      }
    }
    onLinkClick(item){
      const { history, location } = this.props || [];
      let forward = true;
      if(this.state.view==="doc"){
        forward = false;
        this.setState({
          view:"list"
        })
      }
      store.dispatch(onChangeRoute(item,forward));
      var links = store.getState().routes;
      //console.log(links);
      if(item.link!="#" || item.link!=undefined){
        history.replace({
          pathname: item.link
        });
      }
    }
    getTitleHead(){
      return(
          <div className="link-collection">
            <i className="material-icons icon-home">home</i> 
            {
              store.getState().routes.map((val,index,arr) => {
                return <span key={index}><a onClick={(e) => {this.onLinkClick(val)}}>{val.text}</a>{(arr.length>1 && index<(arr.length-1))?<i className="material-icons">keyboard_arrow_right</i>:(null)}</span>        
              })
            }
          </div>
      );
    }
    onRemove(){
      var me = this;
      let collection = store.getState().collection;

      removeSchema(collection._id)
      .then( response =>{
        let {data} = response;
        console.log(data,data.success);
        if(data.success){
            
            me.listarSchemas({});
            me.setState({
              openConfirm:false
            });
        }
      }).catch( err => {
        console.log("ERROR: ",err.message);
      });
    }
    getDisplayMessage(){
      //console.log(typeof store.getState().err);
      return "Error";
    }
  	render(){
      const actions = [
           <FlatButton
             label="No"
             primary={true}
             onClick={() => {this.setState({openConfirm: false})}}/>,
           <FlatButton
             label="Si"
             primary={true}
             onClick={this.onRemove}/>,
         ];
      let {loading} = this.state;   
  		return(
          <div className="collections" style={{"height":"100%"}}>
            <Toolbar className="subToolbar">
                   <ToolbarTitle text={<Breadcrumb/>} />  
                   <ToolbarGroup firstChild={true}>
                   </ToolbarGroup>
                   <ToolbarGroup>
                    { (this.state.view=="list")?<IconButton tooltip="Nuevo" onClick={this.handleNew}>
                        <FontIcon className="material-icons">add_circle</FontIcon>
                      </IconButton>:null
                    }
                   </ToolbarGroup>
            </Toolbar>
            <div className="collection-container">
              {
                (!loading)?
                this.getView():
                <LinearProgress mode="indeterminate" />
              }
            </div>
           <FormNewCollection open={this.state.open} onSave={this.onSave} onClose={this.onClose}/>
           <Dialog
            className="win"
            actions={actions}
            modal={false}
            open={this.state.openConfirm}
            contentStyle={{width:"250px"}}
            onRequestClose={() => {this.setState({openConfirm: false})}}
           >
             Desea eliminar el registro? 
           </Dialog>
           <Snackbar
             open={this.state.openMessage}
             message={this.state.message}
             autoHideDuration={4000}/>
    			</div>
  		)
  	}	
}
export default withRouter(Database);


