<template>
  <div class="material">
    <div class="overflow-x-wrapper">
      <table>
        <tr>
          <td>ID</td>
          <td>{{ id }}<button class="copy-btn" @click="copy(id)">Copy</button></td>
        </tr>
        <tr v-for="(value, key, index) in material" :key="index">
          <td>{{ properties[key] }}</td>
          <td>
            <template v-if="!edit">
              {{ materialEdit[key] || value }}
            </template>
            <input
            v-else
            :type="typeof value === 'number' ? 'number' : 'text'"
            :value="materialEdit[key] || value"
            @input="addToEdited(key, $event.target.value)">
            <button class="copy-btn" @click="copy(value)" v-show="!edit">Copy</button>
          </td>
        </tr>
        <tr v-for="(value, key, index) in uneditable" :key="index + Math.random()">
          <td>{{ properties[key] }}</td>
          <td>
            {{ value }}
            <button class="copy-btn" @click="copy(value)">Copy</button>
          </td>
        </tr>
      </table>
    </div>
    <button
    class="btn btn-green border"
    v-show="!edit"
    @click="edit = true">
      Labot
    </button>
    <button
    class="btn btn-green border"
    v-show="edit"
    @click="updateMaterial">
      Saglabāt
    </button>
    <button
    class="btn btn-yellow border"
    style="margin-left: 5px;"
    v-show="edit"
    @click="materialEdit = {}; edit = false">
      Atcelt
    </button>
    <button
    class="btn btn-red border"
    style="margin-top: 10px; margin-left: 5px;"
    @click="deleteMaterial">
      Dzēst
    </button>
  </div>
</template>

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

export default {
  created() {
    this.getMaterial();
  },
  data() {
    return {
      id: this.$route.params.id,
      material: {},
      uneditable: {},
      materialEdit: {},
      edit: false,
      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)'
      }
    };
  },
  methods: {
    async getMaterial() {
      const material = await API.graphql({
        query: getMaterial,
        variables: { id: this.id }
      });
      let result = material.data.getMaterial;
      if (!result) {
        this.$router.push({ name: 'NotFound' });
      } else {
        this.uneditable.owner = result.owner;
        this.uneditable.createdAt = result.createdAt;
        this.uneditable.updatedAt = result.updatedAt;
        const removable = ['id', 'owner', 'createdAt', 'updatedAt'];
        removable.forEach(x => delete result[x]);
        this.material = result;
      }
    },
    async updateMaterial() {
      const input = {id: this.id};
      for (const [key, value] of Object.entries(this.materialEdit)) {
        input[key] = value;
        this.material[key] = value;
      }
      await API.graphql({
        query: updateMaterial,
        variables: { input }
      });
      this.materialEdit = {};
      this.edit = false;
    },
    async deleteMaterial() {
      API.graphql({
        query: deleteMaterial,
        variables: { input: {id: this.id} }
      }).then(() => this.$router.push({ name: 'Materials' }));
    },
    addToEdited(key, value) {
      if (this.material[key] === value && this.materialEdit[key]) {
        delete this.materialEdit[key];
      } else {
        this.materialEdit[key] = value;
      }
    },
    copy(text) {
      navigator.clipboard.writeText(text).catch(error => {
        console.error(error);
      });
    }
  }
}
</script>

<style scoped>
button:disabled,
button[disabled] {
  opacity: 0.5;
  cursor: default;
}

input:disabled[type="text"],
input[disabled][type="text"] {
  background: none;
  box-shadow: none;
  border-color: transparent;
}

.small-text {
  font-size: 11px;
  font-weight: normal;
}

td input[type="text"] {
  text-align: center;
  font-size: inherit;
  max-width: none;
  border-radius: 5px;
  border: 1px solid #8c8c8c;
  padding: 3px;
  box-shadow: inset 0px 0px 5px #d7dcda;
}

td input[type="number"] {
  text-align: center;
  font-size: inherit;
  max-width: 75px;
  border-radius: 5px;
  border: 1px solid #8c8c8c;
  padding: 3px;
  box-shadow: inset 0px 0px 5px #d7dcda;
}

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