import {DragEvents} from "../../../input/devices/events/DragEvents.js";

/**
 * Attaches drag & drop to an element
 * @param {HTMLElement} el
 * @param {(data: any) => void} data
 */
export function uploadViaElement(el, data) {
    if (!el) throw new Error("Element is required");

    el.addEventListener(DragEvents.DragOver, (e) => {
        // console.log("dragging over element");
        e.preventDefault(); // prevent browser from opening file
    });

    el.addEventListener(DragEvents.Drop, (e) => {
        e.preventDefault();

        const file = e.dataTransfer.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.readAsText(file);
        reader.onload = () => {
            try {
                const text = String(reader.result).replace(/^\uFEFF/, '').trim();
                data(text);
                // console.log("Imported data: ", text);

            } catch (err) {
                console.error("Error reading file: ", err);
            }
        };
    });
}