/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { h } from "@stencil/core";
import { LoaderIcon } from "../../global/assets/loader-icon";
import cn from "../../global/lib/cn";
const cachedImages = {};
const cacheImage = (form, imSrc, id) => {
    fetch(imSrc)
        .then(res => res.blob())
        .then(blob => {
        const reader = new FileReader();
        reader.onloadend = () => {
            cachedImages[id] = reader.result;
            form.rerender({ rerenderForm: true });
        };
        reader.readAsDataURL(blob);
    })
        .catch(e => {
        console.log(e);
        // fail silently, keep fallback
    });
};
let imageSrcBase64 = '';
export const VehicleImageViewer = ({ form }) => {
    var _a, _b, _c, _d;
    form.addWatcher('vehicle');
    let vehicleId = form.getValue('vehicle');
    let openContainer = !!vehicleId;
    const selectedVehicle = (_a = form.context['vehicleList']) === null || _a === void 0 ? void 0 : _a.find(vehicle => vehicle.value === vehicleId);
    let imSrc;
    if (selectedVehicle) {
        imSrc = (_b = selectedVehicle === null || selectedVehicle === void 0 ? void 0 : selectedVehicle.meta) === null || _b === void 0 ? void 0 : _b.image;
        vehicleId = selectedVehicle.value;
    }
    else if (form.context['vehicleList'] && form.context['vehicleList'][0]) {
        imSrc = (_d = (_c = form.context['vehicleList'][0]) === null || _c === void 0 ? void 0 : _c.meta) === null || _d === void 0 ? void 0 : _d.image;
        vehicleId = form.context['vehicleList'][0].value;
    }
    let isLoading = false;
    if (cachedImages[vehicleId]) {
        imageSrcBase64 = cachedImages[vehicleId];
    }
    else if (form && imSrc && vehicleId) {
        cacheImage(form, imSrc, vehicleId);
        isLoading = true;
    }
    return (h("flexible-container", { isOpened: openContainer }, h("div", { style: { 'min-height': '60px' }, part: "vehicle-image-wrapper", class: cn('vehicle-image-wrapper', { loading: isLoading }) }, h("div", { part: cn('vehicle-image-loading-wrapper', { 'vehicle-image-active-loading-wrapper': isLoading }), class: cn('loading-wrapper vehicle-image-loading-wrapper', { 'vehicle-image-active-loading-wrapper': isLoading }) }, h(LoaderIcon, { part: "vehicle-image-loader-icon", class: "img vehicle-image-loader-icon" })), h("img", { alt: "vehicle image", part: "vehicle-image", src: imageSrcBase64, style: { 'border-radius': '6px', 'transition': 'opacity 150ms cubic-bezier(0.4, 0, 0.2, 1);', 'opacity': isLoading ? '0' : '1' } }))));
};
