{% extends 'django_spire/form/field/base_field.html' %}

{% block field_content %}
    <input
            type="text"
            x-model="value"
            x-ref="glue_field"
            hidden
    >

    <div
            class="position-relative"
            x-data="{
            show_dropdown: false,
            files: [],
            objects: {},

            accept: '{{ accept|default:'' }}',
            compression: {{ compression|default:'true' }},
            compression_ratio: {{ compression_ratio|default:'0.75' }},
            disable_camera: '{{ disable_camera|default:'False' }}' === 'True',
            disable_file: '{{ disable_file|default:'False' }}' === 'True',
            maximum_filesize: {{ maximum_filesize|default:'10' }} * 1024 * 1024,
            units: ['B', 'KB', 'MB', 'GB'],

            init() {
                if (!this.value) return;

                try {
                    this.files = Array.isArray(this.value) ? this.value : JSON.parse(this.value);
                } catch(e) {
                    this.files = [];
                }

                this.update_form_files();
            },

            async compress(file, quality = 0.75, maximum_width = 1920) {
                try {
                    let image = await createImageBitmap(file);

                    let scale = Math.min(
                        1,
                        maximum_width / Math.max(image.width, image.height)
                    );

                    let width = image.width * scale;
                    let height = image.height * scale;

                    let canvas = Object.assign(document.createElement('canvas'), { width: width, height: height });
                    let ctx = canvas.getContext('2d');

                    ctx.drawImage(image, 0, 0, width, height);

                    let filename = file.name.replace(/\.[^/.]+$/, '') + '.jpg';

                    return new Promise(result => canvas.toBlob(
                        blob => result(new File([blob], filename, { type: 'image/jpeg' })),
                        'image/jpeg',
                        quality
                    ));
                } catch (error) {
                    console.error('Compression failed:', error);
                    return file;
                }
            },

            format_file_size(bytes) {
                if (!bytes) return '';

                let size = bytes;
                let index = 0;

                while (size >= 1024 && index < this.units.length - 1) {
                    size /= 1024;
                    index++;
                }

                return `${size.toFixed(1)} ${this.units[index]}`;
            },

            take_photo() {
                this.$refs.camera_input.click();
            },

            truncate_name(name, max = 30) {
                return name && name.length > max ? name.slice(0, max - 3) + '...' : name;
            },

            update_form_files() {
                let transfer = new DataTransfer();

                for (let object in this.objects) {
                    transfer.items.add(this.objects[object]);
                }

                this.$refs.upload.files = transfer.files;
            },

            update_value() {
                this.value = this.files.length > 0 ? JSON.stringify(this.files) : null;
            },

            {% block x-data %}{% endblock %}
        }"
    >
        <input
                type="file"
                :name="{{ glue_field }}.name"
                x-ref="upload"
                class="d-none"
                :accept="accept"
                {% block upload_attributes %}{% endblock %}
        >

        <div class="d-flex">
            <button
                    class="form-control text-start d-flex justify-content-between flex-grow-1"
                    type="button"
                    @click="show_dropdown = !show_dropdown"
                    :class="disable_file ? 'd-none' : ''"
            >
                <span class="d-flex flex-wrap align-items-center">
                    {% block selection_display %}{% endblock %}
                </span>

                <span class="d-flex align-items-center">
                    {% include 'django_glue/form/field/element/select_down_arrow_element.html' %}
                </span>
            </button>

            <button
                    type="button"
                    class="btn border ms-2"
                    @click="take_photo()"
                    :class="disable_camera ? 'd-none' : ''"
            >
                <i class="bi bi-camera"></i>
            </button>
        </div>

        <input
                type="file"
                x-ref="file_input"
                class="d-none"
                @change="handle_files_change"
                :accept="accept"
                :class="disable_file ? 'd-none' : ''"
                {% block file_input_attributes %}{% endblock %}
        >

        <input
                type="file"
                x-ref="camera_input"
                class="d-none"
                @change="handle_files_change"
                accept="image/*"
                capture="environment"
                :class="disable_camera ? 'd-none' : ''"
                {% block camera_input_attributes %}{% endblock %}
        >

        <div
                x-cloak
                x-show="show_dropdown"
                @click.outside="show_dropdown = false"
                class="shadow border rounded-2 mt-2 bg-app-glue-layer-one w-100 p-0 list-group"
                style="max-height: 350px; overflow-y: auto;"
        >
            <template x-for="file in files" :key="file.id">
                <div
                        class="py-2 d-flex align-items-center list-group-item px-2 bg-app-glue-layer-one-hover"
                >
                    <div class="me-2" style="width: 40px; height: 40px;">
                        <template x-if="file.preview">
                            <img :src="file.preview" class="img-fluid rounded"
                                 style="max-width: 40px; max-height: 40px; object-fit: cover;">
                        </template>

                        <template x-if="!file.preview">
                            <div class="d-flex align-items-center justify-content-center rounded"
                                 style="width: 40px; height: 40px;">
                                <i class="bi bi-file-earmark"></i>
                            </div>
                        </template>
                    </div>

                    <div class="flex-grow-1 ms-2">
                        <div class="text-truncate" x-text="truncate_name(file.name)"></div>
                        <div class="glue-fs--2" x-text="format_file_size(file.size)"></div>
                    </div>

                    <div class="d-flex align-items-center">
                        <i
                                class="bi bi-trash text-danger glue-cursor-pointer mx-2"
                                @click="remove_file(file.id)"
                        ></i>
                    </div>
                </div>
            </template>

            <div
                    class="m-2 border border-dashed rounded p-3 text-center bg-app-glue-layer-one glue-cursor-pointer"
                    @dragover.prevent="$el.classList.add('border-primary')"
                    @dragleave.prevent="$el.classList.remove('border-primary')"
                    @drop.prevent="$el.classList.remove('border-primary'); handle_files_change({target: {files: $event.dataTransfer.files}})"
                    @click="$refs.file_input.click()"
            >
                <div>
                    <i class="bi bi-cloud-arrow-up me-2"></i>
                    {% block drop_area_text %}{% endblock %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}
