<template>
  <div class="item">
    <div class="overflow-x-wrapper">
      <table>
        <tr v-for="(value, key, index) in item" :key="index">
          <td>{{ properties[key] }}</td>
          <td>{{ value }}<button class="copy-btn" @click="copy(value)">Copy</button></td>
        </tr>
        <tr v-for="extra in extras" :key="extra.name">
          <template v-if="extra.items.length > 0">
            <td>{{ properties[extra.name] }}</td>
            <td>
              <router-link :to="{ name: 'UserItem', params: { user, type: extra.name, id: item.id } }" v-for="item in extra.items" :key="item.id">
                {{ item.name }}
              </router-link>
            </td>
          </template>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import { API } from 'aws-amplify';
import { getWork, getMaterial, getMechanism } from "../graphql/queries";

export default {
  created() {
    this.getItem();
  },
  data() {
    return {
      item: {},
      extras: [],
      user: this.$route.params.user,
      type: this.$route.params.type,
      id: this.$route.params.id,
      properties: {
        name: 'Nosaukums',
        id: 'ID',
        createdAt: 'Izveidošanas datums',
        updatedAt: 'Atjaunošanas datums',
        unit_of_measurement: 'Mērvienība',
        owner: 'Lietotājs',
        manufacturer_name: 'Izstrādātājs',
        amount: 'Daudzums',
        price: 'Cena (EUR)',
        code: 'Kods',
        time_norm: 'Laika norma (c/h)',
        pay_rate: 'Darba samaksas likme (EUR/h)',
        salary: 'Darba alga (EUR)',
        materials: 'Materiāli',
        mechanisms: 'Mehānismi'
      }
    };
  },
  methods: {
    async getItem() {
      var query, extra;
      switch(this.type) {
        case 'works':
          [query, extra] = [{ getWork }, ['materials', 'mechanisms']];
          break;
        case 'materials':
          query = { getMaterial };
          break;
        case 'mechanisms':
          query = { getMechanism };
          break;
        default:
          this.$router.push({ name: 'NotFound' });
      }
      const queryName = Object.keys(query)[0];
      const item = await API.graphql({
        query: query[queryName],
        variables: { id: this.id, owner: this.user }
      });
      let result = item.data[queryName];
      if (!result) this.$router.push({ name: 'NotFound' });
      if (extra) {
        for (let i = 0; i < extra.length; i++) {
          if (result[extra[i]] && result[extra[i]].length > 0) this.extras.push({ items: result[extra[i]], name: extra[i] });
          delete result[extra[i]];
        }
      }
      this.item = result;
    },
    copy(text) {
      navigator.clipboard.writeText(text).catch(error => {
        console.error(error);
      });
    }
  },
  beforeRouteUpdate(to, from, next) {
    this.user = to.params.user;
    this.type = to.params.type;
    this.id = to.params.id;
    this.extras = [];
    next(this.getItem());
  }
}
</script>

<style scoped>
a {
  display: block;
}

.overflow-x-wrapper {
  overflow-x: auto;
  margin: 10px 5px;
}
</style>