<script setup lang="ts">

import {StoredObject, StoredObjectVersion} from "../../types";
import {computed, ref, Ref} from "vue";
import DropFile from "ChillDocStoreAssets/vuejs/DropFileWidget/DropFile.vue";
import DocumentActionButtonsGroup from "ChillDocStoreAssets/vuejs/DocumentActionButtonsGroup.vue";

interface DropFileConfig {
    allowRemove: boolean,
    existingDoc?: StoredObject,
}

const props = withDefaults(defineProps<DropFileConfig>(), {
    allowRemove: false,
});

const emit = defineEmits<{
    (e: 'addDocument', {stored_object: StoredObject, stored_object_version: StoredObjectVersion}): void,
    (e: 'removeDocument'): void
}>();

const has_existing_doc = computed<boolean>(() => {
    return props.existingDoc !== undefined && props.existingDoc !== null;
});

const dav_link_expiration = computed<number|undefined>(() => {
    if (props.existingDoc === undefined || props.existingDoc === null) {
        return undefined;
    }
    if (props.existingDoc.status !== 'ready') {
        return undefined;
    }

    return props.existingDoc._links?.dav_link?.expiration;
});

const dav_link_href = computed<string|undefined>(() => {
    if (props.existingDoc === undefined || props.existingDoc === null) {
        return undefined;
    }
    if (props.existingDoc.status !== 'ready') {
        return undefined;
    }

    return props.existingDoc._links?.dav_link?.href;
})

const onAddDocument = ({stored_object, stored_object_version}: {stored_object: StoredObject, stored_object_version: StoredObjectVersion}): void => {
    emit('addDocument', {stored_object, stored_object_version});
}

const onRemoveDocument = (e: Event): void => {
    e.stopPropagation();
    e.preventDefault();
    emit('removeDocument');
}

</script>

<template>
    <div>
        <drop-file :existingDoc="props.existingDoc" @addDocument="onAddDocument"></drop-file>

        <ul class="record_actions">
            <li v-if="has_existing_doc">
                <document-action-buttons-group
                    :stored-object="props.existingDoc"
                    :can-edit="props.existingDoc?.status === 'ready'"
                    :can-download="true"
                    :dav-link="dav_link_href"
                    :dav-link-expiration="dav_link_expiration"
                />
            </li>
            <li>
                <button v-if="allowRemove" class="btn btn-delete" @click="onRemoveDocument($event)" ></button>
            </li>
        </ul>
    </div>
</template>

<style scoped lang="scss">

</style>
