<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-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
  }),
  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");
    }
  },
  created() {
    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)
        );
      }
    };
    xhttp.open("GET", baseUri + "/users", false);

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

    xhttp.send(null);
    this.users = JSON.parse(sessionStorage.getItem("users"));
  }
};
</script>