import React, { Component } from "react";
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
import Home from "./views/Home";
import Dashboard from "./views/Dashboard";
import Signup from "./views/Signup";
import Login from "./views/Login";
import FourOhFour from "./views/FourOhFour";
import ForgotPass from "./views/Forgot-password";
import ChangePass from "./views/Forgot-pass-reset";
import ConfirmForgotPasswrod from "./views/ConfirmForgotPassword";
import ConfirmRegistration from "./views/ConfirmRegistration";
import ConfirmResetPassword from "./views/ConfirmResetPassword";
import Instruction from "./views/Instruction";
import queryString from "query-string";

import { call } from "./client_server";

/*let userJsonString = JSON.parse(localStorage.getItem("token"));
      let date = new Date().getTime().toString();
      let delta = date - userJsonString.timestamp;
			if (delta < 5*60*60*1000) {
				loggedIn = true;
      }*/

class App extends Component {
  constructor(props) {
    super(props);

    let loggedIn = false;

    try {
      let userJsonString = localStorage.getItem("token");
      let exp = localStorage.getItem("exp");
      let date = new Date().getTime();
      if (userJsonString && exp && date < exp) {
        loggedIn = true;
      } else {
        localStorage.removeItem("token");
        localStorage.removeItem("exp");
      }
    } catch (exception) {}

    this.state = {
      loggedIn: loggedIn,
    };

    this.auth = this.auth.bind(this);
    this.logout = this.logout.bind(this);
  }

  componentDidMount() {
    if (window.location) {
      const values = queryString.parse(window.location.search);
      this.setState({
        query: values,
      });
    } else {
      this.setState({
        query: "ciao",
      });
    }
  }

  auth(data) {
    return call
      .login(data.params)
      .then((res) => {
        if (res.data && res.status === 200) {
          let expire = new Date().getTime() + 60 * 60 * 5 * 1000;
          localStorage.setItem("token", res.data.jwttoken);
          localStorage.setItem("exp", expire);
          call.setToken(res.data.jwttoken);
          this.setState({
            user: data.params.user,
            token: res.data.jwttoken,
            loggedIn: true,
          });
          return res;
          //this.props.history.push("/dashboard");
        } else {
          this.setState({
            error: res.data.message,
          });
          return this.state.error;
        }
      })
      .catch((err) => {
        console.log(err);
        return { status: "Errore" };
      });
  }

  logout() {
    this.setState({
      loggedIn: false,
    });

    localStorage.removeItem("token");
    localStorage.removeItem("exp");
  }

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/login">
            {this.state.loggedIn && this.state.token ? (
              <Redirect tkn={this.state.token} to="/dashboard" />
            ) : (
              <Login auth={this.auth} />
            )}
          </Route>
          <Route path="/signup" exact component={Signup} />
          <Route path="/dashboard">
            {this.state.loggedIn ? (
              <Dashboard tkn={this.state.token} logout={this.logout} />
            ) : (
              <Redirect to="/login" />
            )}
          </Route>
          <Route path="/forgot-password">
            <ForgotPass />
          </Route>
          <Route path="/sent-email">
            <ConfirmForgotPasswrod />
          </Route>
          <Route path="/sent-email-reg">
            <ConfirmRegistration />
          </Route>
          <Route path="/instruction">
            <Instruction />
          </Route>
          <Route path="/forgot-pass-reset"> </Route>
          <Route path="/password-reset">
            <ChangePass query={this.state.query} />
          </Route>
          <Route path="/conf-reset-pass">
            <ConfirmResetPassword />
          </Route>
          <Route component={FourOhFour} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;
