<template>
  <v-container fluid>
    <div v-bind:key="timeTrackAccount.name" v-for="timeTrackAccount in timeTrackAccounts">
      <TimeTrackAccountItem
        v-bind:timeTrackAccount="timeTrackAccount"
        v-on:del-timeTrackAccount="deleteTimeTrackAccount"
        v-on:edit-timeTrackAccount="editTimeTrackAccount"
      />
    </div>
    <v-row>
      <v-col cols="6"></v-col>
      <v-col cols="1">
        <v-btn  v-if="loggedIn == 'true'" fab color="primary" @click="createTimeTrackAccount()">
          <v-icon>mdi-plus</v-icon>
        </v-btn>
      </v-col>
      <v-col cols="5"></v-col>
    </v-row>
  </v-container>
</template>

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

export default {
  name: "TimeTrackAccounts",
  components: {
    TimeTrackAccountItem
  },
  data() {
    return {
      timeTrackAccounts: "",
      loggedIn: sessionStorage.getItem("loggedin")
    };
  },
  methods: {
    deleteTimeTrackAccount(selfLink) {
      var accountxhttp = new XMLHttpRequest();
      accountxhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 204) {
          location.reload();
        }
      };
      accountxhttp.open("DELETE", selfLink , false);

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

      accountxhttp.send(null);
    },
    editTimeTrackAccount(selfLink) {
      sessionStorage.setItem("timeTrackAccountEditSelfLink", selfLink);

      this.$router.push( "/edittimetrackaccount");
    },
    createTimeTrackAccount() {
       this.$router.push( "/createtimetrackaccount");
    }
  },

  created() {
    var accounts;
    var timeTrackAccountsTMP;
    var accountxhttp = new XMLHttpRequest();
    accountxhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        accounts = JSON.parse(accountxhttp.responseText);
        timeTrackAccountsTMP = accounts._embedded.accounts;
      }
    };
    accountxhttp.open(
      "GET",
      baseUri +
        "/accounts/search/findByUsername?username=" +
        sessionStorage.getItem("timeTrackAccountListUser"),
      false
    );

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

    accountxhttp.send(null);

    this.timeTrackAccounts = timeTrackAccountsTMP;
  }
};
</script>

<style scoped>
</style>