<template>
  <div class="select-node-modal-container">
    <h3 class="sub-header">Select supplier</h3>
    <div class="select-node-container">
      <div class="select-node-caption-column">Supplier</div>
      <div class="select-node-input-column select-node-input-field-suppliername">
        <div class="select-node-input-field-suppliername-searchbar">
          <autosuggest-searchbar :fetch-suggestions="fetchSupplier"
                                 placeholder="Find supplier..."
                                 title-resolver="name"
                                 subtitle-resolver="address"
                                 :flag-resolver="resolveFlag"
                                 variant="flags"
                                 @selected="selected"
                                 ref="searchbar"
                                 :initial-value="initialValue"
                                 :activate-watcher="true"
          >
          </autosuggest-searchbar>
        </div>
      </div>
      <div class="select-node-caption-column" v-if="nodeSelected">Address</div>
      <div class="select-node-input-column select-node-input-field-address" v-if="nodeSelected">
        <div class="supplier-flag">
          <flag :iso="isoCode"/>
        </div>
        <div class="supplier-address">{{ supplierAddress }}</div>
      </div>
      <div class="select-node-caption-column" v-if="nodeSelected">Coordinates</div>
      <div class="select-node-input-column" v-if="nodeSelected">{{ coordinatesDMS }}</div>
      <div class="select-node-checkbox" v-if="nodeSelected">
        <checkbox :checked="updateMasterData" @checkbox-changed="checkboxChanged">update master data</checkbox>
      </div>
      <div class="select-node-footer">
        <basic-button :show-icon="false" :disabled="!nodeSelected" @click="action('accept')">OK</basic-button>
        <basic-button variant="secondary" :show-icon="false" @click="action('cancel')">Cancel</basic-button>
      </div>
    </div>
  </div>

</template>

<script>

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

export default {
  name: "SelectNode",
  components: {Checkbox, AutosuggestSearchbar, Flag, InputField, BasicButton},
  emits: ['updateSupplier'],
  props: {
    openSelectDirect: {
      type: Boolean,
      default: false,
    },
    preSelectedNode: {
      type: Object,
      required: false
    },
  },
  created() {
    console.log("SelectNode created with openSelectDirect: " + this.openSelectDirect, this.preSelectedNode);
    if(this.openSelectDirect) {
      this.node = this.preSelectedNode;

    }
  },
  methods: {
    action(action) {
      this.$emit('updateSupplier', {action: action, nodeId: this.node?.id, updateMasterData: this.updateMasterData});
    },
    checkboxChanged(value) {
      this.updateMasterData = value;
    },
    async fetchSupplier(query) {
      console.log("Fetching supplier for query: " + query);
      await this.nodeStore.setQuery({searchTerm: query, nodeType: 'SOURCE', includeUserNode: true});
      return this.nodeStore.nodes;
    },
    resolveFlag(node) {
      return node.country.iso_code;
    },
    selected(node) {
      console.log("Selected node: ", node);
      this.$refs.searchbar.clearSuggestions();
      this.node = node;
    },
    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}`;
    }
  },
  data() {
    return {
      node: null,
      updateMasterData: true,
    }
  },
  computed: {
    ...mapStores(useNodeStore),
    initialValue() {
      if(this.node) {
        return this.node.name;
      } else {
        return '';
      }
    },
    supplierAddress() {
      return this.node?.address ?? '';
    },
    nodeSelected() {
      return this.node != null;
    },
    isoCode() {
      return this.node?.country.iso_code ?? 'DE';
    },
    coordinatesDMS() {
      return `${this.convertToDMS(this.node?.location?.latitude, 'lat')}, ${this.convertToDMS(this.node?.location?.longitude, 'lng')}`;
    }
  }

}
</script>

<style scoped>

.select-node-input-column {
  font-size: 1.4rem;
  color: #6b7280;
  max-width: 30rem;
}

.select-node-input-field-suppliername {
  display: flex;
  gap: 0.8rem;
  align-items: center;
}

.select-node-input-field-suppliername-searchbar {
  flex: 1 1 auto;
  min-width: 50rem;
}

.select-node-modal-container {
  width: 60rem;
  display: flex;
  flex-direction: column;
  gap: 1.6rem;
}

.select-node-container {
  flex: 1 1 auto;
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: repeat(3, fit-content(0));
  align-content: center;
  gap: 1.6rem;
}

.select-node-caption-column {
  font-size: 1.4rem;
  font-weight: 500;
  align-self: center;
  justify-self: end;
  color: #001D33
}

.select-node-footer {
  grid-column: 1 / -1;
  display: flex;
  justify-content: flex-end;
  gap: 1.6rem;
}

.select-node-checkbox {
  grid-column: 1 / -1;
  display: flex;
  justify-content: flex-end;
  gap: 1.6rem;
}

.select-node-input-field-address {
  display: flex;
  gap: 0.8rem;
  align-items: center;
}


.supplier-address {
  font-size: 1.4rem;
  color: #6b7280;
  max-width: 30rem;
}

</style>