<!--
SPDX-FileCopyrightText: WTF Kooperative eG <https://wtf-eg.de/>

SPDX-License-Identifier: AGPL-3.0-or-later
-->

<template>
  <div>
    <label for="searchText" class="form-label fw-bold">{{ label }}</label>
    <div class="row mb-2">
      <div class="col">
        <input
          autocomplete="off"
          type="text"
          class="form-control"
          id="searchText"
          v-model="searchText"
          @keyup="search()"
          @keyup.enter="addResult()"
        />
      </div>
      <div class="col">
        <button
          v-if="searchText != ''"
          type="button"
          class="btn btn-outline-success"
          aria-label="Hinzufügen"
          @click="addResult()"
        >
          <i clas="bi-plus-lg"></i>
          Hinzufügen
        </button>
      </div>
    </div>
    <div class="" v-if="searchResults">
      <ul class="list-group">
        <li
          class="list-group-item"
          v-for="result in searchResults"
          :key="result.id"
          @click="addResult(result)"
        >
          {{ result.name }}
        </li>
      </ul>
    </div>
    <profile-list
      :values="values"
      :type="type"
      :editable="true"
      @remove-value="removeValue($event)"
      @update-values="this.$emit('update-values', this.values)"
    >
    </profile-list>
  </div>
</template>
<script>
import { mapState } from 'vuex'

import RequestMixin from "@/mixins/request.mixin"
import ProfileList from "@/components/ProfileList";

export default {
  name: "AutoComplete",
  mixins: [RequestMixin],
  components: {
    ProfileList,
  },
  props: {
    type: {
      type: String,
    },
    label: {
      type: String,
    },
    values: {
      type: Array,
    },
  },
  data() {
    return {
      iconUrl: this.apiUrl,
      searchText: "",
      searchResults: [],
      showErrorMessage: false,
    };
  },
  computed: {
    ...mapState(['currentUserId'])
  },
  methods: {
    addResult(result = false) {
      if (!result) result = this.searchResults[0];
      if (
        this.values.map((item) => item[this.type].name).includes(result.name)
      ) {
        return false;
      }

      let changeValues = Object.assign(this.values);
      let newValue = {
        profile_id: this.currentUserId,
      };
      if (this.type != "contacttype") {
        newValue.level = 1;
      } else {
        newValue.content = "";
      }
      newValue[this.type] = result;
      changeValues.unshift(newValue);
      this.searchText = "";
      this.searchResults = [];
      this.$emit("update-values", changeValues);
    },
    removeValue(valueName) {
      const newValues = this.values.filter((value) => {
        if (valueName === value[this.type].name) {
          return false;
        } else {
          return true;
        }
      });
      this.$emit("update-values", newValues);
    },
  },
};
</script>
