<template>
  <v-container fluid>
    <div v-bind:key="user.username" v-for="user in users">
      <UsersItems v-bind:user="user" v-on:edit-user="edituser" v-on:del-user="deluser" v-on:show-accounts="showAccounts"/>
    </div>
     <v-row>
      <v-col cols="5"></v-col>
       <v-col cols="1">
        <v-btn v-if="havePrevPage == true" @click="prevPage()">
          <v-icon>mdi-arrow-left</v-icon>
        </v-btn>
      </v-col>
      <v-col cols="1">
        <v-btn v-if="haveNextPage == true" @click="nextPage()">
          <v-icon>mdi-arrow-right</v-icon>
        </v-btn>
      </v-col>     
      <v-col cols="5"></v-col>
    </v-row>
  </v-container>
</template>

<script>
import { baseUri} from "../variables.js";
import UsersItems from "./UsersItems.vue";
export default {
  components: {
    UsersItems
  },
  data: () => ({
    users: JSON.parse(sessionStorage.getItem("users")),
    dialog: false,
    page: sessionStorage.getItem("page"),
      haveNextPage: "",
      havePrevPage: ""
  }),
  methods: {
    edituser(userlink) {
     
      sessionStorage.setItem("edituser", userlink);

      this.$router.push( "/edituser");
    },
    deluser(selfLink){
       var userxhttp = new XMLHttpRequest();
      userxhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 204) {
          location.reload();
        }
      };
      userxhttp.open("DELETE", selfLink , false);

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

      userxhttp.send(null);
    },
    showAccounts(username, uid) {
      sessionStorage.setItem("timeTrackAccountListUser", username);
      sessionStorage.setItem("timeTrackAccountListUserId", uid);

      this.$router.push("/timetrackaccounts");
    },
    nextPage() {
      var pageTMP = parseInt(this.page) + 1;
      sessionStorage.setItem("page", pageTMP);
      location.reload();
    },
    prevPage() {
      var pageTMP = parseInt(this.page) - 1;
      sessionStorage.setItem("page", pageTMP);
      location.reload();
    }
  },
  created() {
    var userLinks;
      if (this.page == null) {
      this.page = 0;
    }
    sessionStorage.removeItem("page");
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var usersInformation = JSON.parse(xhttp.responseText);     
        sessionStorage.setItem(
          "users",
          JSON.stringify(usersInformation._embedded.users)
        );
         userLinks = usersInformation._links;
      }
    };
    xhttp.open("GET", baseUri + "/users?page=" +this.page, false);

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

    xhttp.send(null);
       if (userLinks.next != undefined) {
      this.haveNextPage = true;
    }
    if (userLinks.prev != undefined) {
      this.havePrevPage = true;
    }
    this.users = JSON.parse(sessionStorage.getItem("users"));
  }
};
</script>