<template>
  <div id="codes">
    <Menu></Menu>

    <div class="page">
      <router-link to="codes/add" class="pure-button pure-button-primary">{{ $t('admin.codes.add') }}</router-link>

      <div v-if="codes !== null">
        <div class="pure-g list-header">
          <div class="pure-u-3-4">{{ $t('admin.codes.code') }}</div>
          <div class="pure-u-1-4">{{ $t('admin.codes.owner') }}</div>
        </div>

        <div v-for="code in codes" class="list">
          <div class="pure-g row">
            <div class="pure-u-3-4">{{ code.id }}</div>
            <div class="pure-u-1-4">{{ code.username }}</div>
          </div>
        </div>

        <div v-if="codes.length == 0" class="nodata">
          {{ $t('admin.empty') }}
        </div>
      </div>

      <div v-else class="loading">
        {{ $t('admin.loading') }}
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Menu from './Menu.vue';
import shared from '../../shared';

export default {
  data()
  {
    return {
      codes: null
    };
  },

  components: {
    Menu
  },

  created()
  {
    var self = this;

    if (!shared.token)
    {
      self.$router.push('/admin');
      return;
    }


    axios.get('/admin/codes', {
      headers: {
        Authorization: 'Bearer ' + shared.token
      }
    })
    .then((response) =>
    {
      self.codes = response.data;
    })
    .catch((error) =>
    {
      if (error.response && error.response.status == 403)
      {
        shared.token = null;
        self.$router.push('/admin');
      }
      else
        shared.$emit('showNotification', error.message);
    });
  }
}
</script>

<style lang="scss">
</style>