<template>
    <div class="a-playlist-editor">
        <a-select-file ref="select-file"
            :title="labels && labels.add_sound"
            :labels="labels"
            :list-url="soundListUrl"
            :deleteUrl="soundDeleteUrl"
            :uploadUrl="soundUploadUrl"
            :uploadLabel="labels.select_file"
            @select="selected"
            >
            <template #upload-preview="{upload}">
                <slot name="upload-preview" :upload="upload"></slot>
            </template>
            <template #upload-form>
                <slot name="upload-form"></slot>
            </template>
            <template #default="{item}">
                <audio controls :src="item.url"></audio>
                <label class="label small flex-grow-1">{{ item.name }}</label>
            </template>
        </a-select-file>

        <a-form-set ref="formset" :form-data="formData" :labels="labels"
                :initials="initData.items"
                order-by="position"
                :action-add="actionAdd">
            <template v-for="[name,slot] of rowsSlots" :key="slot"
                    v-slot:[slot]="data">
                <slot v-if="name != 'row-tail'" :name="name" v-bind="data"/>
            </template>

            <template #row-sound="{item,inputName}">
                <label>{{ item.data.name }}</label><br>
                <audio controls :src="item.data.url"/>
                <input type="hidden" :name="inputName" :value="item.data.sound"/>
            </template>
        </a-form-set>
    </div>
</template>
<script>
import AFormSet from './AFormSet'
import ASelectFile from "./ASelectFile"

export default {
    components: {AFormSet, ASelectFile},

    props: {
        formData: Object,
        labels: Object,
        // initial datas
        initData: Object,

        soundListUrl: String,
        soundUploadUrl: String,
        soundDeleteUrl: String,
    },

    computed: {
        rowsSlots() {
            return Object.keys(this.$slots)
                .filter(x => x.startsWith('row-') || x.startsWith('rows-') || x.startsWith('control-'))
                .map(x => [x, x.startsWith('rows-') ? x.slice(5) : x])
        },
    },

    methods: {
        actionAdd() {
            this.$refs['select-file'].open()
        },

        selected(item) {
            const data = {
                "sound": item.id,
                "name": item.name,
                "url": item.url,
                "broadcast": item.broadcast,
            }
            this.$refs.formset.set.push(data)
         },
    },
}
</script>
