<template>
  <div class="app">
    <v-app id="geotimetracking">
      <!-- Side navigation menu  -->
      <v-navigation-drawer v-model="drawer" app clipped class="main_accent">
        <v-list dense>
          <v-list-item link to="/">
            <v-list-item-action>
              <v-icon>mdi-view-dashboard</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>Home</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
          <v-list-item link to="/timerecords" v-bind:class="{'d-none':loggedIn=='false'}">
            <v-list-item-action>
              <v-icon>mdi-clock</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>Time Records</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
          <v-list-item link to="/statistics" v-bind:class="{'d-none':loggedIn=='false'}">
            <v-list-item-action>
              <v-icon>mdi-chart-bar</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>Statistics</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
          <v-list-item @click="toAccounts" v-bind:class="{'d-none':loggedIn=='false'}">
            <v-list-item-action>
              <v-icon>mdi-account-details</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>Accounts</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
          <v-list-item link to="/about">
            <v-list-item-action>
              <v-icon>mdi-information-outline</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>About</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
          <v-list-item link to="/users" v-bind:class="{'d-none':loggedIn=='false'}">
            <v-list-item-action>
              <v-icon>mdi-account-group</v-icon>
            </v-list-item-action>
            <v-list-item-content>
              <v-list-item-title>Admin</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </v-list>
      </v-navigation-drawer>

      <!-- Top menu bar -->
      <v-app-bar app clipped-left class="main" elevation="10">
        <v-app-bar-nav-icon @click.stop="drawer = !drawer" />
        <v-img @click="forward" src="./assets/logo.svg" max-height="100%" max-width="100" contain></v-img>
        <v-toolbar-title>Geo Timetracking</v-toolbar-title>
        <v-spacer></v-spacer>

        <!-- Menu with account icon -->
        <v-menu
          v-model="menu"
          :close-on-content-click="false"
          :nudge-width="200"
          offset-y
          v-if="loggedIn == 'true'"
        >
          <template v-slot:activator="{ on }">
            <v-btn icon v-on="on">
              <v-icon>mdi-account</v-icon>
            </v-btn>
          </template>

          <v-card>
            <v-list>
              <v-list-item>
                <v-list-item-avatar>
                  <img src="https://cdn.vuetifyjs.com/images/john.jpg" alt="John" />
                </v-list-item-avatar>

                <v-list-item-content>
                  <v-list-item-title>{{fullname}}</v-list-item-title>
                </v-list-item-content>

                <v-list-item-action></v-list-item-action>
              </v-list-item>
            </v-list>

            <v-divider></v-divider>


            <v-card-actions>
              <v-spacer></v-spacer>

              <v-btn text @click="menu = false">Cancel</v-btn>
              <v-btn color="primary" text @click="logout">Logout</v-btn>
            </v-card-actions>
          </v-card>
        </v-menu>
        <v-card v-if="loggedIn == 'false'">
          <!-- Modal -->

          <v-row justify="center">
            <v-dialog v-model="dialog" width="70%" persistent>
              <template v-slot:activator="{ on }">
                <v-btn color="primary" dark v-on="on">Login</v-btn>
              </template>
              <v-card class="main">
                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn icon @click="dialog = false">
                    <v-icon>mdi-window-close</v-icon>
                  </v-btn>
                </v-card-actions>
                <SignIn v-on:signIn="signIn" v-on:signUp="signUp" />
                <p id="loginError"></p>
              </v-card>
            </v-dialog>
          </v-row>
        </v-card>
      </v-app-bar>

      <!-- Routed pages are inserted here -->
      <v-content>
        <router-view />
      </v-content>

      <!-- Footer on bottom -->
      <v-footer app class="main">
        <span>&copy; 2020 Team TacocaT</span>
      </v-footer>
    </v-app>
  </div>
</template>

<script>
import SignIn from "./views/SignIn.vue";
import { baseUri } from "./variables.js";

if (!sessionStorage.getItem("loggedin")) {
  sessionStorage.setItem("loggedin", false);
}

export default {
  components: {
    SignIn
  },
  props: {
    source: String
  },
  data: () => ({
    drawer: null,    
    dialog: false,
    menu: false,
    loggedIn: sessionStorage.getItem("loggedin"),
    fullname:
      sessionStorage.getItem("firstname") +
      " " +
      sessionStorage.getItem("lastname")
  }),
  methods: {
    forward() {
      this.$router.push("/");
    },
    signIn(loginData) {
      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function() {
        if ((this.status == 200) & (this.readyState == 4)) {
          sessionStorage.setItem(
            "jwt",
            this.getResponseHeader("Authorization")
          );
          sessionStorage.setItem("loggedin", true);
        } else if (this.status != 200 && this.status != 0) {
          document.getElementById("loginError").innerHTML =
            "Login not successfull";
        }
      };

      xhttp.open("POST", baseUri + "/login", false);
      xhttp.send(
        '{"username": "' +
          loginData.username +
          '", "password": "' +
          loginData.password +
          '"}'
      );
      if (sessionStorage.getItem("loggedin") == "true") {
        sessionStorage.setItem("haveData", true);
        var whoxhttp = new XMLHttpRequest();
        whoxhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            var userInformation = JSON.parse(whoxhttp.responseText);
            sessionStorage.setItem("firstname", userInformation.firstname);
            sessionStorage.setItem("lastname", userInformation.lastname);
            sessionStorage.setItem("username", userInformation.username);
            sessionStorage.setItem("userIDOwn", userInformation.id);

            this.fullname =
              sessionStorage.getItem("firstname") +
              " " +
              sessionStorage.getItem("lastname");
            location.reload();
          }
        };
        whoxhttp.open("GET", baseUri + "/whoami", false);

        whoxhttp.setRequestHeader(
          "Authorization",
          sessionStorage.getItem("jwt")
        );

        whoxhttp.send(null);
        location.reload();
      }
    },
    signUp(signupData) {
      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function() {
        if ((this.status == 201) & (this.readyState == 4)) {
          location.reload();
        } else if (this.status != 201 && this.status != 0) {
          document.getElementById("loginError").innerHTML =
            "The username already exist";
        }
      };
      xhttp.open("POST", baseUri + "/sign-up", true);
      xhttp.setRequestHeader("Content-Type", "application/json");
      xhttp.send(
        "{" +
          '"firstname": "' +
          signupData.firstname +
          '", "lastname": "' +
          signupData.lastname +
          '", "username": "' +
          signupData.username +
          '", "password": "' +
          signupData.password +
          '"}'
      );
    },
    logout() {
      sessionStorage.clear();
      sessionStorage.setItem("loggedin", false);
      location.reload();
    },
    toAccounts() {
      sessionStorage.setItem(
        "timeTrackAccountListUser",
        sessionStorage.getItem("username")
      );
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var usersInformation = JSON.parse(xhttp.responseText);
          sessionStorage.setItem(
            "timeTrackAccountListUserId",
            usersInformation._links.self.href
          );
        }
      };
      xhttp.open(
        "GET",
        baseUri +
          "/users/search/byUsername?username=" +
          sessionStorage.getItem("username"),
        false
      );

      xhttp.setRequestHeader("Authorization", sessionStorage.getItem("jwt"));

      xhttp.send(null);
      this.users = JSON.parse(sessionStorage.getItem("users"));
      
      if (this.$route.path == "/timetrackaccounts" ) {
      
      
      location.reload();
        
      }else{
        this.$router.push("/timetrackaccounts");
      }
    }
  },

  created() {
    this.$vuetify.theme.dark = true;
  }
};
</script>


<style scoped>
.link {
  color: #f1f1f1f1;
  text-decoration: none;
}
.v-application {
  font-family: "Montserrat", sans-serif;
  background-color: var(--v-background-base) !important;
}
</style>
