import React, { Component } from 'react';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import LinearProgress from 'material-ui/LinearProgress';
import {
  AppCode,
  Breadcrumb,
  AppCard
} from "../../components/index.jsx";

import Dialog from 'material-ui/Dialog';
import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar';
import Constants from "../../helper/Constants.jsx"
import Helper from "../../helper/Helper.jsx"

import store from '../../store.jsx'
import { onEdit, onSelected } from  "../../actions/CollectionActions.jsx";
import { onChangeRoute, onSaveCollection, onGetCollection,
onMessage, getCollections } from  "../../actionCreators.jsx";

import axios from 'axios';

class Collection  extends Component {
  constructor(props) {
    super(props);
    this.state = {
        _id:null,
        view:"list",
        open: true,
        loading:false,
        disabled:false,
        openConfirm:false,
        collection:null,
        doc:{},
        collections:[],
        routes:[],
        alias:"",
        name:"",
        config:"",
        lang:""
      };
      this.collection = {};
      const { history, location } = this.props || [];
      //this.state["collection"] = location.state.collection;
      axios.defaults.headers.common['Authorization'] = localStorage.token;
      axios.defaults.headers['Content-Type'] = 'application/json';


      this.handleEditar = this.handleEditar.bind(this);
      this.handleRemove = this.handleRemove.bind(this);
      this.onRemove = this.onRemove.bind(this);
      this.listCollection = this.listCollection.bind(this);
      this.getCollectionByAlias = this.getCollectionByAlias.bind(this);
      this.handleSave = this.handleSave.bind(this);
      this.handleNew = this.handleNew.bind(this);
  }
  componentDidMount() {
    this.setState({
      config:vkbeautify.json('{ "name":"String", "apellido":{"type":"String","required":"true"}}')
    });
    const {collection} = this.props;
  }
  componentWillMount(){
    let props = this.props;
    var me = this;
    let isEmpty = false;
    let match = location.hash.match(/(\/)\w+/g);  
    
    let name = Helper.getHashParam(location.hash,1);
    let alias = Helper.getHashParam(location.hash,2);
    let _id = Helper.getHashParam(location.hash,3);

    store.subscribe(() => {
      let _state = store.getState();
      if(_state){
        let {routes,view} = _state;
        this.setState({
            routes,
            disabled:(typeof(_state.code_error)!="undefined" && _state.code_error!=="")
        });
      }
      //console.log("Collection State: ",routes);
    });
    

    this.setState({loading:true});
    //Obtener Collection por alias
    this.getCollectionByAlias(alias).
    then((response) => {

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

        
        if(collection.config){
          let config = JSON.parse(collection.config);
          isEmpty = (Helper.isEmpty(config));
          if(isEmpty){
            store.dispatch(onChangeRoute());
            store.dispatch(onChangeRoute({text:"Collections",link:"/database"}));
            store.dispatch(onChangeRoute({text:name,link:"/database/"+name}));

            const { history, location } = this.props || [];
            history.replace({
              pathname: "/database/"+name
            });
            return;
          }
        }

        me.setState({
            view:"list",
            alias:collection.alias,
            ...state
        });
        store.dispatch(onChangeRoute());
        store.dispatch(onChangeRoute({text:"Collections",link:"/database"}));
        store.dispatch(onChangeRoute({text:alias,link:"/collection/"+name+"/"+alias}));
        store.dispatch(onChangeRoute({text:name,link:"/database/"+name}));
        
        if(_id){
          store.dispatch(onChangeRoute({text:_id,link:"/collection/"+name+"/"+alias+'/'+_id}));
        }
        
        //Listar Documentos
        this.listCollection()
        .then((collections) => {
            me.setState({
              collections
            });            
        });
      }else{
        let collection = response.data; 
        if(collection.config){
          let config = JSON.parse(collection.config);
          isEmpty = (Helper.isEmpty(config));
          if(isEmpty){
            store.dispatch(onChangeRoute());
            store.dispatch(onChangeRoute({text:"Collections",link:"/database"}));
            store.dispatch(onChangeRoute({text:name,link:"/database/"+name}));

            const { history, location } = this.props || [];
            history.replace({
              pathname: "/database/"+name
            });
            return;
          }
        }
        me.setState({
          collection,
          alias
        });
        store.dispatch(onChangeRoute());
        store.dispatch(onChangeRoute({text:"Collections",link:"/database"}));
        store.dispatch(onChangeRoute({text:collection.alias,link:"/collection/"+collection.name+"/"+alias}));
        store.dispatch(onChangeRoute({text:collection.name,link:"/database/"+collection.name}));
        
        if(_id){
          store.dispatch(onChangeRoute({text:_id,link:"/collection/"+collection.name+"/"+collection.alias+'/'+_id}));
        }   
        console.log("Collection _id: ",collection,_id);
        //Listar Documentos
        this.listCollection(_id)
        .then((collections) => {

          

          if(_id){
            console.log("Collection: ",collections);
            

            me.setState({
              view:"doc",
              collection:collections
            })
          }else{
            me.setState({
              collections
            });            
          }
        });
      }
    });
  }
  getCollectionByAlias(alias){
    const me = this;
    return new Promise((resolve,reject) => {
        axios.get("/admin/get_collection_by_alias", {
          params:{
            alias
          },
          headers: {
            'Content-Type': 'application/json',
            'Authorization':localStorage.token
          }          
        })
        .then(function (response) {
          
          resolve(response);
        })
        .catch(function (error) {
          reject(error);
        });
    });
  }
  listCollection(_id){
    var me = this;
    return new Promise(function(resolve,reject){
      axios.get("/admin/"+me.state.alias+((_id!=undefined)?"/"+_id:""), {
        headers: {
          'Content-Type': 'application/json',
          'Authorization':localStorage.token
        }
      })
      .then(function (response) {
        var result = response.data;

        me.setState({loading:false});
        
        resolve(result.data);
      })
      .catch(function (error) {
        //console.log(error);
        reject(error);
      });

    });
  }
  componentWillReceiveProps(nextProps,context) {
    // //console.log("Collection props: ",nextProps);
    this.setState({
      ...nextProps
    });
  }
  getTitleHead(){
    // const routes = JSON.parse(localStorage.routes);
    
    let { routes } = this.state;
    //console.log("--->Links: ",routes);
    return(

        <div className="link-collection">
          <i className="material-icons icon-home">home</i> 
          {
            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>
    );
  }
  onLinkClick(item){
    const { history, location } = this.props || [];
    let forward = true;
    if(item.link!="#"){
      if(this.state.view==="doc"){
        forward = false;
        this.setState({
          view:"list"
        });
      }
      store.dispatch(onChangeRoute(item,forward));
      history.replace({
        pathname: item.link
      });
    }
  }
  handleEditar(collection){
    let {location:{state}} = this.props;
    if(state){
      console.log("VIENE DE ROUTE!",name);
    }
    let match = location.hash.match(/(\/)\w+/g);  
    
    let name = Helper.getHashParam(location.hash,1);
    let alias = Helper.getHashParam(location.hash,2);

    const { history } = this.props || [];
    history.replace({
      pathname: "/collection/"+name+"/"+alias+'/'+collection._id,
      state:{
        collection,
        name,
        alias,
        view:"doc"
      }
    });
    /*this.setState({
      collection,
      view:"doc"
    });*/
  }
  handleRemove(collection){
    store.dispatch(onSelected(collection));
    this.setState({
      openConfirm:true
    });
  }
  handleSave(){
    var me = this;
    const { history } = this.props || [];
    let match = location.hash.match(/(\/)\w+/g);  
    let name = Helper.getHashParam(location.hash,1);
    let alias = Helper.getHashParam(location.hash,2);

    let collection = store.getState().collection || this.state.collection || this.state.doc;
    /*if(typeof store.getState().code_error!=""){
        store.dispatch(onMessage({
            open:true,
            msg:store.getState().code_error
        }));
        return;
    }*/
    return new Promise(function(resolve,reject){

      let isEmpty = false;
      if(collection){
        isEmpty = (Helper.isEmpty(collection));
        if(isEmpty){
          store.dispatch(onMessage({
              open:true,
              msg:"El documento no puede estar vacio."
          }));
          reject("El documento no puede estar vacio.");
          return;
        }
      }
      if(me.state.view==="new"){


        axios.post("/admin/"+me.state.alias, collection)
        .then(function (response){
            var result = response.data;
          if(result.success){

              store.dispatch(onMessage({
                  open:true,
                  msg:result.msg
              }));

              me.listCollection(result._id)
              .then((collection) => {
                store.dispatch(onChangeRoute({text:result._id,link:"/collection/"+collection.name+"/"+collection.alias+'/'+result._id}));
                history.replace({
                  pathname: "/collection/"+name+"/"+alias+'/'+result._id,
                  state:{
                    collection,
                    name,
                    alias,
                    view:"doc"
                  }
                }); 
                resolve(result.data);               
              }).catch(function (error) {
                reject(error);
              });
          }else{
            store.dispatch(onMessage({
                open:true,
                msg:result.msg.toString()
            }));
            reject(result.msg);
          }
        });
      }else{
        axios.put("/admin/"+me.state.alias+"/"+me.state.collection._id, collection)
        .then(function (response) {
          var result = response.data;

          if(result.success){
            store.dispatch(onMessage({
                open:true,
                msg:result.msg
            }));

            me.listCollection()
            .then((collections) => {
              me.setState({
                collections
              });
            });

            resolve(result.data);
          }else{
            store.dispatch(onMessage({
                open:true,
                msg:result.msg.toString()
            }));
            reject(result.msg);
          }
        })
        .catch(function (error) {
          //console.log(error);
          reject(error);
        });
      }
    });
  }
  onRemove(){
    var me = this;
    let _id = store.getState().collection._id;
    const { history } = me.props || [];

    return new Promise(function(resolve,reject){
      axios.delete("/admin/"+me.state.alias+"/"+_id, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization':localStorage.token
        }
      })
      .then(function (response) {
        var result = response.data;

        me.listCollection()
        .then((collections) => {

          store.dispatch(onMessage({
              open:result.success,
              msg:result.msg
          }));

          me.setState({
            collections,
            openConfirm:false
          });
        });
        resolve(result.data);
      })
      .catch(function (error) {
        //console.log(error);
        reject(error);
      });
    });
  }
  handleNew(){
   this.setState({
     collection:{},
     view:"new",
   }); 
  }

  getView(){

    let match = location.hash.match(/(\/)\w+/g);  
    let name = Helper.getHashParam(location.hash,1);
    let alias = Helper.getHashParam(location.hash,2);

    switch(this.state.view){
      case "list":
        return(
          <div className={(this.state.collections.length==0)?"empty-collection":""}>
        {
          (this.state.collections.length>0)?
          this.state.collections.map((val,index) => {
            return(<AppCard 
                  key={index}
                  title={<span style={{color:"#397AA5"}}>ObjectId(<span style={{color:"#c0c0c0"}}>{val._id}</span>)</span>}
                  actions={[
                    <IconButton tooltip="Eliminar" onClick={() => {this.handleRemove(val)}}>
                      <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}
                  onChange={(val,editor) => {
                    try{
                      val = vkbeautify.json(val);
                      this.setState({
                        "value":val
                      });
                    }catch(e){};
                  }} />
            </AppCard>)
          }):
          <h2>Click en el botón <i className="material-icons empty-plus">add_circle</i>para agregar documentos.</h2>
        }</div>);
      break;
      case "doc":
        return(
          <div style={{"height":"100%"}}>
          <AppCard 
            className="code-item code-edit" 
            title={<div><span><b>EDICIÓN: </b></span><span style={{color:"#397AA5"}}>ObjectId(<span style={{color:"#c0c0c0"}}>{this.state.collection._id}</span>)</span></div>}
            expanded={true}
            editable={true}
            actions={[
               <IconButton tooltip="Guardar" onClick={this.handleSave} disabled={this.state.disabled}>
                <FontIcon className="material-icons icon-tool">save</FontIcon>
              </IconButton>
            ]}
            >
            <AppCode
            editor="docs"
            readOnly={false}
            config={this.state.collection}/>
          </AppCard>
          </div>
        )
      break;
      default:
        return(
          <div style={{"height":"100%"}}>
          <AppCard 
            className="code-item code-new" 
            title={<div><span><b>CREACIÓN: </b></span><span>Nuevo {name}</span></div>}
            expanded={true}
            editable={true}
            actions={[
               <IconButton tooltip="Guardar" onClick={this.handleSave} disabled={this.state.disabled}>
                <FontIcon className="material-icons icon-tool">save</FontIcon>
              </IconButton>
            ]}
            >
            <AppCode
            readOnly={false}
            editor="docs"
            config={this.state.collection}/>
          </AppCard>
          </div>
        )
      break;
    }
  }
  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>
        <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>
        <Dialog
           className="win"
           actions={actions.map((item,index) => {
            return <span key={index}>{item}</span>
           })}
           modal={false}
           open={this.state.openConfirm}
           contentStyle={{width:"250px"}}
           onRequestClose={() => {this.setState({openConfirm: false})}}>
            Desea eliminar el registro? 
        </Dialog>
      </div>
    )
  } 
}
export default Collection;


