/** @odoo-module **/

import { registry } from "@web/core/registry";
import { Many2ManyBinaryField, many2ManyBinaryField } from "@web/views/fields/many2many_binary/many2many_binary_field";
import { useFileViewer } from "@web/core/file_viewer/file_viewer_hook";

export class InspectionPhotoField extends Many2ManyBinaryField {
    setup() {
        super.setup();
        this.fileViewer = useFileViewer();
    }

    get viewableFiles() {
        return this.files
            .filter((f) => this.isImage(f))
            .map((f) => ({
                name: f.name,
                isImage: true,
                isViewable: true,
                downloadUrl: `/web/content/${f.id}?download=true`,
                defaultSource: `/web/image/${f.id}`,
            }));
    }

    onClickImage(fileId) {
        const viewable = this.viewableFiles;
        const clicked = viewable.find(
            (vf) => vf.defaultSource === `/web/image/${fileId}`
        );
        if (clicked) {
            this.fileViewer.open(clicked, viewable);
        }
    }
}

InspectionPhotoField.template = "fusion_rental.InspectionPhotoField";

export const inspectionPhotoField = {
    ...many2ManyBinaryField,
    component: InspectionPhotoField,
};

registry.category("fields").add("inspection_photos", inspectionPhotoField);
