<template>
  <div class="create-new-node-container">
    <h3 class="sub-header">Create new supplier</h3>
    <form @submit.prevent>
      <div class="create-new-node-form-container">
        <div class="input-field-caption">Name:</div>
        <div>
          <div class="text-container"><input class="input-field" v-model="nodeName"/></div>
        </div>
        <div></div>
        <div class="input-field-caption">Address:</div>
        <div>
          <div class="text-container"><input class="input-field" v-model="nodeAddress" @input="checkChange"/></div>
        </div>
        <div>
          <basic-button icon="SealCheck" @click.prevent="verifyAddress" :disabled="addressVerified" @submit.prevent>
            Check address
          </basic-button>
        </div>
        <div class="input-field-caption" v-if="addressVerified">Country:</div>
        <div class="country-field" v-if="addressVerified">
          <flag :iso="nodeIso"/>
          {{ nodeCountry }}
        </div>
        <div v-if="addressVerified"></div>
        <div class="input-field-caption" v-if="nodeCoordinates && addressVerified">Coordinates:</div>
        <div class="coordinate-field" v-if="nodeCoordinates && addressVerified">{{ coordinatesDMS }}</div>
      </div>
      <div class="supplier-map" v-if="nodeCoordinates && addressVerified">
        <open-street-map-embed :coordinates="nodeCoordinates" :zoom="15" width="100%" height="300px"
                               custom-filter="grayscale(0.8) sepia(0.5) hue-rotate(180deg) saturate(0.5) brightness(1.0)"></open-street-map-embed>
      </div>
      <div class="create-new-node-footer">
        <basic-button @click.prevent="send" variant="primary" :show-icon="false" :disabled="unverified">Create
        </basic-button>
        <basic-button @click.prevent="cancel" variant="secondary" :show-icon="false">Cancel</basic-button>
      </div>
    </form>
  </div>
</template>

<script>

import BasicButton from "@/components/UI/BasicButton.vue";
import {mapStores} from "pinia";
import {useNodeStore} from "@/store/node.js";
import OpenStreetMapEmbed from "@/components/UI/OpenStreetMapEmbed.vue";
import Flag from "@/components/UI/Flag.vue";

export default {
  name: "CreateNewNode",
  components: {Flag, OpenStreetMapEmbed, BasicButton},
  emits: ['created', 'close'],
  data() {
    return {
      nodeName: "",
      nodeAddress: "",
      nodeCoordinates: null,
      nodeCountry: null,
      nodeIso: null,
      addressVerified: false,
      verifiedAddress: null,
      node: null
    }
  },
  computed: {
    coordinatesDMS() {

      if (this.nodeCoordinates != null && typeof this.nodeCoordinates === 'object') {
        return `${this.convertToDMS(this.nodeCoordinates?.latitude, 'lat')}, ${this.convertToDMS(this.nodeCoordinates?.longitude, 'lng')}`;
      }
      return '';
    },
    ...mapStores(useNodeStore),
    unverified() {
      return !this.addressVerified || !this.nodeName;
    },

  },
  methods: {
    convertToDMS(coordinate, type) {

      if (!coordinate)
        return '';

      let direction;
      if (type === 'lat') {
        direction = coordinate >= 0 ? 'N' : 'S';
      } else {
        direction = coordinate >= 0 ? 'E' : 'W';
      }

      // Arbeite mit Absolutwert
      const abs = Math.abs(coordinate);

      // Grad (ganzzahliger Teil)
      const degrees = Math.floor(abs);

      // Minuten
      const minutesFloat = (abs - degrees) * 60;
      const minutes = minutesFloat.toFixed(4);


      return `${degrees}° ${minutes}' ${direction}`;
    },
    checkChange() {
      this.addressVerified = this.nodeAddress === this.verifiedAddress;
    },
    async verifyAddress() {
      const {node: node, error: error} = await this.nodeStore.locate(this.nodeAddress);

      this.nodeCoordinates = null;
      this.nodeIso = null;
      this.nodeCountry = null;
      this.addressVerified = false;
      this.verifiedAddress = null;

      if (error === null && node !== null) {
        this.nodeCoordinates = node.location;
        this.nodeAddress = node.address;

        this.nodeIso = node.country.iso_code;
        this.nodeCountry = node.country.name;

        this.addressVerified = true;
        this.verifiedAddress = node.address;
        this.node = node;
      }

    },
    async send() {
      const node = await this.nodeStore.addNode(this.nodeName, this.nodeAddress, this.nodeCoordinates, this.node.country);
      this.$emit("created", node);
    },
    cancel() {
      this.$emit("close");
    }
  }
}
</script>

<style scoped>

.create-new-node-map {
  display: flex;
  justify-content: center;
}

.supplier-map {
  display: flex;
  justify-content: center;
  flex: 1;
  padding: 1.6rem;
}


.sub-header {
  font-weight: normal;
  font-size: 1.4rem;
  color: #6B869C;
  margin-bottom: 1.6rem;
}

.input-field-caption {
  font-size: 1.2rem;
  font-weight: 500;
  align-self: center;
  justify-self: end;
  color: #001D33
}

.coordinate-field {
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #6b7280;
}

.country-field {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.8rem;
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #6b7280;
}

.input-field {
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #002F54;
  width: 100%;
  min-width: 5rem;
}

.text-container {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 0.4rem;
  padding: 0.6rem 1.2rem;
  /* box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);*/
  border: 0.2rem solid #E3EDFF;
  transition: all 0.1s ease;
  flex: 1 0 auto;
}

.text-container:hover {
  background: #EEF4FF;
  border: 0.2rem solid #8DB3FE;
  /*transform: translateY(2px);*/
  transform: scale(1.01);
}


.create-new-node-container {
  width: 60rem;
}

.create-new-node-footer {
  display: flex;
  gap: 1.6rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.create-new-node-form-container {
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 1.6rem;

}

</style>