<script setup lang="ts">
import { Address } from "ChillMainAssets/types";
import SearchBar from "ChillMainAssets/vuejs/AddressPicker/Component/SearchBar.vue";
import {
    AddressAggregated,
    AssociatedPostalCode,
    getAddressesAggregated,
    getPostalCodes,
} from "ChillMainAssets/vuejs/AddressPicker/driver/local-search";
import { Ref, ref } from "vue";

interface AddressPickerProps {
    suggestions?: Address[];
}

const props = withDefaults(defineProps<AddressPickerProps>(), {
    suggestions: () => [],
});

const addresses: Ref<AddressAggregated[]> = ref([]);
const postalCodes: Ref<AssociatedPostalCode[]> = ref([]);
let abortControllerSearchAddress: null | AbortController = null;
let abortControllerSearchPostalCode: null | AbortController = null;

const onSearch = async function (search: string): Promise<void> {
    performSearchForAddress(search);
    performSearchForPostalCode(search);
};

const performSearchForAddress = async (search: string): Promise<void> => {
    if (null !== abortControllerSearchAddress) {
        abortControllerSearchAddress.abort();
    }

    if ("" === search) {
        addresses.value = [];
        abortControllerSearchAddress = null;
        return;
    }

    abortControllerSearchAddress = new AbortController();

    console.log("onSearch", search);
    try {
        addresses.value = await getAddressesAggregated(
            search,
            abortControllerSearchAddress,
        );
        abortControllerSearchAddress = null;
    } catch (e: unknown) {
        if (e instanceof DOMException && e.name === "AbortError") {
            console.log("search aborted for:", search);

            return;
        }

        throw e;
    }
};

const performSearchForPostalCode = async (search: string): Promise<void> => {
    if (null !== abortControllerSearchPostalCode) {
        abortControllerSearchPostalCode.abort();
    }

    if ("" === search) {
        addresses.value = [];
        abortControllerSearchPostalCode = null;
        return;
    }

    abortControllerSearchPostalCode = new AbortController();

    console.log("onSearch", search);
    try {
        postalCodes.value = await getPostalCodes(
            search,
            abortControllerSearchPostalCode,
        );
        abortControllerSearchPostalCode = null;
    } catch (e: unknown) {
        if (e instanceof DOMException && e.name === "AbortError") {
            console.log("search postal code aborted for:", search);

            return;
        }

        throw e;
    }
};
</script>

<template>
    <search-bar @search="onSearch"></search-bar>
    <p>test</p>
    <p v-for="a in addresses" :key="a.row_number">
        {{ a.street }}, positions: {{ a.positions[0] }}
    </p>
    <p v-for="pc in postalCodes" :key="pc.postcode_id">{{ pc }}</p>
</template>

<style scoped lang="scss"></style>
