import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { Container, Row, Col } from 'reactstrap';
import {  BrowserRouter as Router, Redirect, HashRouter, Route, Switch } from 'react-router-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {red500, greenA200,cyan500,blue500,lightBlue500,grey50} from 'material-ui/styles/colors';
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import Snackbar from 'material-ui/Snackbar';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import AppBar from 'material-ui/AppBar';
import {
	AppHeader,
	AppSidebar
} from '../components/index.jsx';
import routes from '../routes.jsx';
import Constants from '../helper/Constants.jsx';
import axios from 'axios';

const muiTheme = getMuiTheme({
  palette: {
    textColor: grey50,
    primaryText:grey50,
    primary1Color:blue500
  },
  appBar: {
    height: 50,
  },
});
import { onMessage, onItemTap } from '../actionCreators.jsx';
import store from '../store.jsx';

const items = [
  {
    text:"Ver todos los proyectos",
    name:"show_all_projects",
    value:1
  },
  {
    text:"Agregar un proyecto",
    name:"add_project",
    value:2
  }
];
class AppPanel  extends Component {
  constructor(props) {
      super(props);
      this.state = {
        open: false,
        openMessage:false,
        message:{
          "msg":"",
          "open": false
        },
        error:"",
        _state:{},
        value:1,
        count:0,
        defaultHashTag:Constants.defaultHashTag,
        name:"Database",
        currentPath:{},
        routes,
        user:null,
        token:""
      };
      
      this.onRedirect = this.onRedirect.bind(this);
      this.currentPath = this.currentPath.bind(this);
      this.handleItemClick = this.handleItemClick.bind(this);
      this.handleClick = this.handleClick.bind(this);
      this.handleRequestClose = this.handleRequestClose.bind(this);
      this.handleActionClick = this.handleActionClick.bind(this);
    }
    onRedirect(){

      //console.log(this.currentPath());
      if(store.getState()!=undefined){
        if(!this.isLoggedIn()){
          return "/login";
        }else{

          return this.state.defaultHashTag;
        }
      }else{
        return "/login";
      }
    }

    currentPath(){
      const { history } = this.props || [];
      const hash = window.location.hash.split("#")[1].toLowerCase();
      let current_path = routes.filter(function(val,index){
        return (val.path === history.location.pathname || val.path === hash);
      })[0];
      if(current_path!=undefined){
        this.setState({
          "currentPath":current_path,
          "name":current_path.name
        });
      }else{
        current_path = this.state.defaultHashTag;
      }
      return current_path;
    }
    componentWillMount() {
      const { history } = this.props || [];
      const me = this;
      let current_path = this.currentPath();
      
      localStorage.setItem("routes",JSON.stringify(routes));
      console.log("Loaded!");

      let {location:{state}} = me.props;
      if(state){
        let {active_group} = state;
        console.log("Active Group: ",active_group);
      }

      store.subscribe(() => {
        let _state = store.getState();
        let {name} = _state;
        //Titulo del Panel
        if(name){
          console.log("Name: ",name);
          this.setState({name});
        }

        if(typeof(_state.message)!=="undefined"){
          this.setState({
            open:_state.message.open,
            message:{
              "msg":(typeof(_state.message.msg)!="undefined")?_state.message.msg:"",
              "open":_state.message.open,
              className:""
            }
          });
        }else if(typeof(_state.error)!="undefined"){
          this.setState({
            open:(_state.error!=""),
            message:{
              "msg":(typeof(_state.error)!="undefined")?_state.error:"",
              "open":(_state.error!=""),
              className:"error-message"
            }
          });
        }
      });

      let pathname = Constants.defaultHashTag;
      let route = routes.filter(item => {
        return (item.path === pathname);
      }).map(item => {
        return { "name": item.name, "path":item.path};
      })[0];
      if(route){
        console.log(route);
        this.setState({
          "name":route.name
        });
      }


      axios.defaults.headers.common['Authorization'] = localStorage.token;
      axios.defaults.headers.common['token'] = localStorage.token;
      axios.defaults.timeout = 600000;
      axios.interceptors.response.use(null, function(err) {
        let {data:{msg,success},status} = err.response;
        switch(status){
          case 401://Session caducada
            msg = msg || err.message;

            me.setState({
              message:{
                "duration":0,
                "open":true,
                "msg":msg
              }
            });
            localStorage.clear();
            history.replace("/login");
          break;
          default:
            let error = "ERROR: "+err.message;
            if(!success){
              error = msg;
            }
            me.setState({
              message:{
                "open":true,
                "msg":error
              }
            });
          break;
        }
        return Promise.reject(err);
      });

      if (!localStorage.user) {
        if(history.location!=undefined){
          //console.log("NO Esta logeado!");  
          if(history.location.pathname!="/login"){
              //history.replace("/login");
          }
        }
      }else{
        
        this.setState({
          routes,
          //openMessage:(store.getState().message!=undefined)?store.getState().message.open:false,
          //message:(store.getState().message!=undefined)?store.getState().message.msg:""
        });
        //console.log(history.location.pathname);
        if(history.location!=undefined){
          if(history.location.pathname=="\/"){
              //history.replace(this.state.defaultHashTag);
          }
        }
      }
    }
    
    isLoggedIn(){
      if(typeof(store.getState())!== "undefined"){
        return (typeof(store.getState().user)!== "undefined");
      }else{
        return (typeof(localStorage.getItem("user"))!== "undefined");
      }
    }
    handleActionClick(){
      this.setState({
        message:{
          "open":false,
          "msg":""
        }
      });
    }
    handleRequestClose(){
      store.dispatch(onMessage({
          open:false,
          msg:""
      }));
    }
    handleItemClick(item){
      switch(item.name){
        case "show_all_projects":

          const { match, history } = this.props
          history.push({
              pathname: '/projects',
              state: {
              }
          });

        break;
      }
    }
    getCurrentPath(){
      const { match, history } = this.props
      
      let pathname = history.location.pathname;

      if(pathname!='/'){
        pathname = history.location.pathname;
      }else{
        pathname = Constants.defaultHashTag;
      }
      return pathname;
    }
    handleClick = () => {
      this.setState({
        message:{open: false,msg:""}
      });
    };

    render(props){
      return(
        <MuiThemeProvider muiTheme={muiTheme}>
          <Container fluid className="App">
            <Row>
              <Col className="col-left" sm="2" style={{"margin": 0, "paddingRight": 0}}>
                <AppSidebar  routes={this.state.routes}/>
              </Col>
              <Col className="col-right" xs="10" style={{"margin": 0, "paddingLeft": 0}}>
                  <div className="app-panel">
                    <AppHeader items={items} count={this.state.count} handleItemClick={this.handleItemClick}/>
                    <AppBar className="AppToolbar" showMenuIconButton={false} title={this.state.name}/>
                    <div className="app-panel-container">
                      <Switch>
                          {this.state.routes.map((route, idx) => {
                              return route.component ? (<Route 
                                key={idx} path={route.path} 
                                exact={route.exact} 
                                name={route.name} 
                                render={props => (
                                  <route.component {...props} />
                                )} />)
                                : (null);
                            }
                          )}
                          <Redirect from="/" to="/database"/>
                      </Switch>
                      <div>
                        <Snackbar
                            className={"message "+this.state.message.className}
                            open={this.state.message.open}
                            action="OK"
                            autoHideDuration={(this.state.message.duration)?this.state.message.duration:4000}
                            message={this.state.message.msg}
                            onActionClick={this.handleActionClick}
                            onRequestClose={this.handleRequestClose}/>
                      </div>
                  </div>
              </div>
              </Col>
            </Row>
          </Container>
        </MuiThemeProvider>
    )
  } 
}
export default withRouter(AppPanel);