<template>
  <div id="code">
    <div v-if="code !== null">
      <form class="pure-form pure-form-aligned">
        <fieldset>
          <div class="pure-control-group" v-if="code.id">
            <label for="codeId">{{ $t('admin.codes.detail.code') }}</label>
            <input id="codeId" type="text" readonly :value="code.id" class="pure-input-2-3">
          </div>
          <div class="pure-form-description" v-if="code.id">
            <div>{{ $t('admin.codes.detail.codeHint') }}</div>
            <a :href="getCodeUrl(code.id)" target="_blank">{{ getCodeUrl(code.id) }}</a>
          </div>

          <!--
          <div class="pure-control-group" v-if="code.id">
            <label for="user">{{ $t('admin.codes.detail.owner') }}</label>
            <input id="user" type="text" readonly :value="code.username" class="pure-input-2-3">
          </div>
          -->

          <div class="pure-control-group" v-if="code.id">
            <label for="created">{{ $t('admin.codes.detail.created') }}</label>
            <input id="created" type="text" readonly :value="code.created | formatDateTime" class="pure-input-2-3">
          </div>

          <div class="pure-control-group">
            <label for="description">{{ $t('admin.codes.detail.description') }}</label>
            <input id="description" type="text" v-model="code.description" class="pure-input-2-3">
          </div>
          <div class="pure-form-description">
            {{ $t('admin.codes.detail.descriptionHint') }}
          </div>

          <div class="pure-control-group">
            <label for="expiration">{{ $t('admin.codes.detail.expiration') }}</label>
            <select v-if="!code.id" id="expirationUnits" v-model="code.expiration.units" class="pure-input-1-3">
              <option value="" v-if="allowExpiration(null)">{{ $t('admin.codes.detail.expirationUnits.never') }}</option>
              <option value="h" v-if="allowExpiration('h')">{{ $t('admin.codes.detail.expirationUnits.h') }}</option>
              <option value="d" v-if="allowExpiration('d')">{{ $t('admin.codes.detail.expirationUnits.d') }}</option>
              <option value="w" v-if="allowExpiration('w')">{{ $t('admin.codes.detail.expirationUnits.w') }}</option>
              <option value="M" v-if="allowExpiration('M')">{{ $t('admin.codes.detail.expirationUnits.M') }}</option>
              <option value="y" v-if="allowExpiration('y')">{{ $t('admin.codes.detail.expirationUnits.y') }}</option>
            </select>
            <input v-if="!code.id" id="expiration" type="number" v-model="code.expiration.value" :disabled="!code.expiration.units" min="1" class="pure-input-1-3">

            <input v-if="code.id" id="expiration" type="text" readonly :value="getExpirationValueUnits(code.expiration)" class="pure-input-2-3">
          </div>
          <div v-if="code.id" class="pure-control-group">
            <label for="expirationDate"></label>
            <input id="expirationDate" type="text" readonly :value="code.expirationDate | formatDateTime" class="pure-input-2-3">
          </div>
          <div class="pure-form-description" v-if="!code.id && maxExpiration !== null">
            {{ $t('admin.codes.detail.expirationHint', { valueUnits: getExpirationValueUnits(maxExpiration) }) }}
          </div>

          <div class="pure-control-group">
            <label for="message">{{ $t('admin.codes.detail.message') }}</label>
            <textarea id="message" type="text" v-model="code.message" class="pure-input-2-3" rows="10"></textarea>
          </div>
          <div class="pure-form-description">
            {{ $t('admin.codes.detail.messageHint') }}
          </div>
          <div class="pure-form-description">
            <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank">Markdown Cheatsheet</a>
          </div>

          <div class="pure-controls">
            <button class="pure-button pure-button-primary" @click="save" :disabled="saving">{{ $t('admin.save') }} <fa icon="spinner" pulse v-if="saving"></fa></button>
            <router-link to="/admin/codes" class="pure-button">{{ $t('admin.cancel') }}</router-link>
          </div>
        </fieldset>
      </form>
    </div>
  </div>
</template>

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

export default {
  data()
  {
    return {
      code: null,
      maxExpiration: null,
      saving: false
    };
  },

  props: ['codeParam'],


  watch: {
    '$route' (to, from)
    {
      var self = this;
      self.checkCode();
    }
  },


  created()
  {
    var self = this;
    self.checkCode();
  },

  methods: {
    checkCode()
    {
      var self = this;

      if (self.codeParam)
      {
        axios.get('/admin/codes/' + encodeURIComponent(self.codeParam), {
          headers: {
            Authorization: 'Bearer ' + shared.adminToken
          }
        })
        .then((response) =>
        {
          self.code = response.data;
        })
        .catch((error) => { shared.$emit('apiError', error, this.$router) });
      }
      else
      {
        axios.get('/admin/expiration', {
          headers: {
            Authorization: 'Bearer ' + shared.adminToken
          }
        })
        .then((response) =>
        {
          self.maxExpiration = response.data.max !== null ? {
            units: response.data.max.units,
            value: response.data.max.value
          } : null;

          self.code = {
            expiration: response.data.default !== null ? {
              units: response.data.default.units,
              value: response.data.default.value
            } : {
              units: '',
              value: 1
            },
            message: null
          };
        })
        .catch((error) => { shared.$emit('apiError', error, this.$router) });
      }
    },

    getCodeUrl(code)
    {
      var port = ':' + window.location.port;

      if ((window.location.protocol == 'http:' && window.location.port == 80) ||
          (window.location.protocol == 'https:' && window.location.port == 443))
        port = '';

      return window.location.protocol + '//' +
             window.location.hostname + port + '/c/' +
             encodeURIComponent(code);
    },

    save()
    {
      var self = this;

      // TODO check against maxExpiration, otherwise the server will simply throw a 400 Bad Request

      self.saving = true;

      axios.post('/admin/codes', {
        id: self.code.id,
        expiration: self.code.expiration.units ? self.code.expiration : null,
        description: self.code.description,
        message: self.code.message
      }, {
        headers: {
          Authorization: 'Bearer ' + shared.adminToken
        }
      })
      .then((response) =>
      {
        if (self.code.id)
          this.$router.push('/admin/codes');
        else
          this.$router.push('/admin/codes/edit/' + response.data);
      })
      .catch((error) => { shared.$emit('apiError', error, this.$router) })
      .then(() =>
      {
        self.saving = false;
      });
    },

    allowExpiration(units)
    {
      var self = this;

      if (units === null)
        return self.maxExpiration === null;

      if (self.maxExpiration === null)
        return true;

      let validUnits = ['h', 'd', 'w', 'M', 'y'];
      return validUnits.indexOf(units) <= validUnits.indexOf(self.maxExpiration.units);
    },


    getExpirationValueUnits(expiration)
    {
      var self = this;

      if (expiration === null)
        return '';

      return self.$tc('expirationValues.' + expiration.units,
        expiration.value,
        { count: expiration.value });
    }
  }
}
</script>