﻿isDeleteMode = false;
function getSelectedDropdownDetails() {
    var selectedOption = $('#markupTextOptionsDropdown option:selected');
    var value = selectedOption.val();
    var dataType = selectedOption.attr('datatype');
    var id = selectedOption.attr('id'); // Assuming the id attribute is set

    return {
        value: value,
        dataType: dataType,
        id: id
    };
}

async function saveShapes(id) {
    const mapElement = document.getElementById('imageAsMap');
    if (!mapElement || !mapElement.mapInstance) {
        console.error('VectorPhoto: saveShapes - no map instance found');
        return null;
    }

    let element = document.getElementById(id);
    if (element == null) {
        console.error('VectorPhoto: saveShapes - image element not found:', id);
        return null;
    }

    const map = mapElement.mapInstance;
    const features = map.getLayers().getArray()[1].getSource().getFeatures();
    const points = features.map(feature => {
        const coords = feature.getGeometry().getCoordinates();
        const details = feature.getProperties();
        return {
            X: coords[0],
            Y: coords[1],
            Text: details.name,
            DataType: details.dataType,
            Id: details.id
        };
    });

    return {
        Points: JSON.stringify(points),
        NaturalWidth: element.naturalWidth,
        NaturalHeight: element.naturalHeight
    };
}

function cleanupPhotoMarker() {
    const mapElement = document.getElementById('imageAsMap');
    if (mapElement && mapElement.mapInstance) {
        try {
            mapElement.mapInstance.setTarget(null);
        } catch (e) { }
        mapElement.mapInstance = null;
    }
}

function createCustomStyle(text, hovered = false) {
    const fillColor = hovered ? 'rgba(0, 255, 0, 0.3)' : 'rgba(0, 0, 0, 0)';
    return new ol.style.Style({
        text: new ol.style.Text({
            text: text,
            font: '16px Arial',
            fill: new ol.style.Fill({
                color: '#000',
            }),
            backgroundFill: new ol.style.Fill({
                color: '#fff',
            }),
            padding: [2, 2, 2, 2],
            offsetX: 20,
            offsetY: 0,
            placement: 'point',
        }),
        image: new ol.style.RegularShape({
            points: 150,
            radius: 15,
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 3,
            }),
            fill: new ol.style.Fill({
                color: fillColor,
            }),
        }),
        zIndex: 100
    });
}
function createInnerCircleStyle() {
    return new ol.style.Style({
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
                color: 'green',
            }),
        }),
        zIndex: 100
    });
}

async function initPhotoMarker(id, dotNetObjRef, hiddenFieldMarkups) {
    isDeleteMode = false;
    $('#delete-mode-text').text('Delete Mode');

    if (hiddenFieldMarkups) {
        var markups = JSON.parse(hiddenFieldMarkups);
    }

    let element = document.getElementById(id);

    if (element == null) {
        console.error('VectorPhoto: initPhotoMarker - image element not found:', id);
        return false;
    }

    // Wait for image to load if it hasn't yet
    if (!element.complete || element.naturalWidth === 0) {
        try {
            await new Promise((resolve, reject) => {
                const onLoad = () => { cleanup(); resolve(); };
                const onError = () => { cleanup(); reject(new Error('Image failed to load')); };
                const cleanup = () => {
                    element.removeEventListener('load', onLoad);
                    element.removeEventListener('error', onError);
                };
                element.addEventListener('load', onLoad);
                element.addEventListener('error', onError);
                setTimeout(() => { cleanup(); reject(new Error('Image load timeout')); }, 15000);
            });
        } catch (e) {
            console.error('VectorPhoto: initPhotoMarker - image load failed:', e);
            return false;
        }
    }

    if (element.naturalWidth === 0 || element.naturalHeight === 0) {
        console.error('VectorPhoto: initPhotoMarker - image has zero dimensions');
        return false;
    }

    // Ensure target container exists
    const mapElement = document.getElementById('imageAsMap');
    if (!mapElement) {
        console.error('VectorPhoto: initPhotoMarker - #imageAsMap not found');
        return false;
    }

    // Clean up previous map instance
    if (mapElement.mapInstance) {
        try {
            mapElement.mapInstance.setTarget(null);
        } catch (e) { }
        mapElement.mapInstance = null;
    }

    const source = new ol.source.Vector();
    if (markups != undefined) {
        markups.forEach((point, index) => {
            var x = point.xPosition * element.naturalWidth;
            var y = point.yPosition * element.naturalHeight;
            var text = point.label;
            const feature = new ol.Feature({
                geometry: new ol.geom.Point([x, y]),
                name: text,
                dataType: point.dataType,
                id: point.id
            });
            feature.setStyle([
                createCustomStyle(text),
                createInnerCircleStyle()
            ]);
            source.addFeature(feature);
        });
    }

    const vector = new ol.layer.Vector({
        source: source,
        style: function (feature) {
            const text = feature.get('text');
            return new ol.style.Style({
                text: new ol.style.Text({
                    text: text,
                    font: '12px Arial',
                    fill: new ol.style.Fill({
                        color: '#000'
                    }),
                    backgroundFill: new ol.style.Fill({
                        color: '#fff'
                    }),
                    padding: [2, 2, 2, 2],
                    offsetX: 20,
                    offsetY: -10,
                    placement: 'point',
                }),
                image: new ol.style.Circle({
                    radius: 10,
                    stroke: new ol.style.Stroke({
                        color: 'green',
                        width: 2,
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(0, 0, 0, 0)',
                    }),
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    fill: new ol.style.Fill({
                        color: 'green'
                    }),
                }),
                zIndex: 100
            });
        },
    });

    const extent = [0, 0, element.naturalWidth, element.naturalHeight];
    const projection = new ol.proj.Projection({
        units: 'pixels',
        extent: extent,
    });

    const map = new ol.Map({
        layers: [
            new ol.layer.Image({
                source: new ol.source.ImageStatic({
                url: element.src,
                projection: projection,
                imageExtent: extent}),
            }),vector],
        target: 'imageAsMap',
        view: new ol.View({
            projection: projection,
            center: ol.extent.getCenter(extent),
            zoom: 2,
            maxZoom: 8,
        }),
    });

    mapElement.mapInstance = map;

    // Ensure map renders correctly after DOM layout settles
    setTimeout(() => { try { map.updateSize(); } catch(e) {} }, 200);

    $("#delete").click(function () {
        if (isDeleteMode) {
            isDeleteMode = false;

            $('#delete-mode-text').text('Delete Mode');
            map.addInteraction(draw);
            return;
        }

        isDeleteMode = true;

        $('#delete-mode-text').text('Exit Delete Mode');
        map.removeInteraction(draw);
    });

    function addInteractions() {
        draw = new ol.interaction.Draw({
            source: source,
            type: 'Point',
            style: function () {
                const details = getSelectedDropdownDetails();
                return [createCustomStyle(details.value), createInnerCircleStyle()];
            }
        });

        draw.on('drawend', function (event) {
            const feature = event.feature;
            const details = getSelectedDropdownDetails();
            feature.setProperties({
                name: details.value,
                dataType: details.dataType,
                id: details.id
            });

            feature.setStyle([createCustomStyle(details.value), createInnerCircleStyle()]);
        });

        map.addInteraction(draw);
        map.on('pointermove', function(event) {
            const coordinates = event.coordinate;
            const minX = 0;
            const minY = 0;
            const maxX = element.naturalWidth;
            const maxY = element.naturalHeight;

            if ((coordinates[0] < minX || coordinates[0] > maxX || coordinates[1] < minY || coordinates[1] > maxY) || isDeleteMode) {
                map.removeInteraction(draw);
            } else if (!map.getInteractions().getArray().includes(draw)) { 
                map.addInteraction(draw);
            }
        });

        map.on('click', function (event) {
            if (isDeleteMode) {
                map.forEachFeatureAtPixel(event.pixel, function (feature) {
                    source.removeFeature(feature);
                });
            }
        });
    }

    addInteractions();

    return true;
}