<template>
  <v-container class="green lighten-5">
        <PromotionNavbar />
        <v-snackbar v-model="snackbar" top timeout="3000">
                <span>{{snackbarText}}</span>
        </v-snackbar>
        <div>
            <v-data-table 
                :headers="headers"
                :items="promotions"
                item-key="id"
                class="mt-5 light-green lighten-2"
                :search="search"
                >
                <template v-slot:top>
                    <v-text-field
                v-model="search"
                label="Search"
                class="mx-4"
                ></v-text-field>
                </template>
            </v-data-table>
        </div>
  </v-container>
</template>

<script>

import { getToken } from '../../security/token.js'
import PromotionNavbar from '../../components/navbar/PromotionNavbar.vue'

export default {
    name: 'CurrentPromotions',
    components : {
      PromotionNavbar
    },
    data() {
        return {
            promotions: [],
            snackbarText : "",
            pharmacyAddress : "",
            search: '',
            snackbar : false,  
            
        }
    },
    computed: {
      headers () {
        return [
          { text: 'Medicine', value: 'medicineName'},
          { text: 'Pharmacy', value: 'pharmacyName'},
          { text: 'Promotion', value: 'text' },
          { text: 'Start', value: 'timeInterval.startTime' },
          { text: 'End', value: 'timeInterval.endTime' },
        ]
      },
    },
    methods: {
        loadPromotions() {
            this.$http.get("promotion/all-current",{
                headers : {
                        Authorization: 'Bearer ' + getToken()
                    }
            })
            .then(response => {
                    console.log(response.data.status);
                    this.promotions = response.data;
                    for(let i = 0; i < this.promotions.length; i++){
                    var startDate = new Date(this.promotions[i].timeInterval.startTime)
                    var endDate = new Date(this.promotions[i].timeInterval.endTime)
                    this.promotions[i].timeInterval.startTime = startDate.toString().substring(4,24);
                    this.promotions[i].timeInterval.endTime = endDate.toString().substring(4,24);
                }
            })
            .catch((error) => {
                if (error.response.status === 404) {
                    this.snackbar = true
                    this.snackbarText = "There is no promotions!";
                }else if(error.response.status === 401){
                    this.snackbar = true
                    this.snackbarText = "Unauthorized!";
                }else{
                    this.snackbar = true
                    this.snackbarText = "Server error occured!";
                }
            });
        },
    },
    mounted() {
        this.loadPromotions();
    }
}
</script>

<style>

</style>