<script setup lang="ts">
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import * as path from '@tauri-apps/api/path';
import { open } from '@tauri-apps/plugin-dialog';
import { usePrfStore } from '../stores';

const props = defineProps({
    placeholder: String,
    directory: Boolean,
    promptname: String,
    extension: String,
    value: String,
    callback: Function,
});

const prf = usePrfStore();

const filePick = async () => {
    const exePath = prf.current?.data.sgt.target;
    let defaultPath: string | undefined;
    if (
        exePath !== undefined &&
        exePath.length > 0 &&
        props.value !== undefined &&
        !(await path.isAbsolute(props.value))
    ) {
        defaultPath = await path.join(exePath, '..');
        defaultPath = await path.join(defaultPath, props.value);
        defaultPath = await path.join(defaultPath, '..');
    }
    const res = await open({
        multiple: false,
        directory: props.directory,
        defaultPath,
        filters:
            props.promptname && props.extension
                ? [
                      {
                          name: props.promptname,
                          extensions: [props.extension],
                      },
                  ]
                : [],
    });
    if (res != null && props.callback !== undefined) {
        props.callback(res);
        /*path.relative(prf.current?.data.sgt.target ?? '', res) */
    }
};
</script>

<template>
    <Button icon="pi pi-folder-open" size="small" @click="filePick" />
    <InputText
        size="small"
        :placeholder="placeholder"
        type="text"
        :model-value="value"
        @update:model-value="(value) => callback && callback(value)"
    />
</template>
