<script setup lang="ts">
import type { CommandDefinition } from '@/composables/command.ts';
import { ref } from 'vue';
import CommandParameter from '@/components/CommandParameter.vue';
import FlexDivider from '@/components/FlexDivider.vue';
import type { DynamicDataType } from '@/composables/dynamic.ts';
import { parseJsonString, toJsonString } from '@/composables/json.ts';

const props = defineProps<{
    command: CommandDefinition | null;
}>();

const parameters = ref<{ [key: string]: DynamicDataType }>({});
const busy = ref(false);
const result = ref('');

async function sendCommand() {
    const command = props.command;
    const params = parameters.value;
    if (!command) {
        return;
    }
    busy.value = true;
    result.value = 'Loading...';

    const response = await fetch(`/api/cmd/${command.name}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: toJsonString(params),
    });
    const text_response = await response.text();
    if (response.ok) {
        result.value = parseJsonString(text_response);
    } else {
        result.value = text_response;
    }
    busy.value = false;
}
</script>

<template>
    <div class="row" v-if="!command">
        <span> No Command Selected </span>
    </div>
    <template v-else>
        <div class="row">
            <span>
                {{ command.name }}
            </span>
        </div>
        <FlexDivider></FlexDivider>
        <CommandParameter
            v-for="param in command.parameters"
            :key="param.name"
            :parameter="param"
            v-model="parameters[param.name]"
        ></CommandParameter>
        <div class="row">
            <button :disabled="busy" @click.stop.prevent="sendCommand">
                Send
            </button>
        </div>
        <div class="row shrink grow"></div>
        <div class="row">{{ result }}</div>
    </template>
</template>

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