var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _EdenFileManager_assetsUrl, _EdenFileManager_isMounted, _EdenFileManager_initToken, _EdenFileManager_render, _EdenFileManager_loadImages, _EdenFileManager_preloadImage, _EdenFileManager_loadFiles, _EdenFileManager_navigate, _EdenFileManager_select, _EdenFileManager_openCropper, _EdenFileManager_goHome, _EdenFileManager_goBack, _EdenFileManager_removeItem, _EdenFileManager_addFolder, _EdenFileManager_renameItem, _EdenFileManager_rotateImage, _EdenFileManager_moveItem, _EdenFileManager_handleUpload, _EdenFileManager_handleActions, _EdenFileManager_checkActions, _EdenFileManager_spawnLoader, _EdenFileManager_destroyLoader, _EdenFileManager_initialize;
import EdenModal from "../common/eden-modal.js";
import template, { imagePreviewTemplate, } from "./eden-file-manager.template.js";
import styles from "./eden-file-manager.styles.js";
import html from "../../services/html.js";
import { createFolder, cropItem, moveItem, moveList, removeItem, renameItem, rotateImage, } from "../../services/api.js";
import { snackbar } from "../common/eden-snackbar.js";
import EdenImageCropper from "./eden-image-cropper.js";
import EdenStructureTree from "../structure/eden-structure-tree.js";
import structureTreeStyles from "../styles/eden-structure-tree-styles.js";
import { EdenEvents } from "../../services/event.js";
import { buildFileManagerImageSrc, encodeFileManagerCropMetadata, loadFileManagerData, parseFileManagerMetadata, resolvePreviousBreadcrumbPath, uploadFilesToCurrentPath, } from "./eden-file-manager-flow.js";
import { dispatchFileManagerAction } from "./eden-file-manager-actions.js";
import t from "../../i18n/index.js";
class EdenFileManager extends HTMLElement {
    constructor({ modal, callback, width, height, uploadOnly, metadata, }) {
        super();
        _EdenFileManager_assetsUrl.set(this, "https://eden-files.jeantinland.com");
        _EdenFileManager_isMounted.set(this, false);
        _EdenFileManager_initToken.set(this, 0);
        _EdenFileManager_render.set(this, (list = {}, storage = {}, coldStart = true) => {
            if (this.breadcrumb) {
                this.breadcrumb.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
            }
            if (this.list) {
                this.list.removeEventListener("dblclick", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
                this.list.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_select, "f"));
            }
            if (this.actions) {
                this.actions.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_handleActions, "f"));
            }
            __classPrivateFieldGet(this, _EdenFileManager_destroyLoader, "f").call(this);
            this.selectedItem = null;
            this.innerHTML = html `
      <style>
        ${styles}
      </style>
      ${template(list, storage, this.width, this.height, this.uploadOnly, coldStart)}
    `;
            this.actions = this.querySelector(".actions");
            __classPrivateFieldGet(this, _EdenFileManager_checkActions, "f").call(this);
            if (coldStart) {
                __classPrivateFieldGet(this, _EdenFileManager_loadImages, "f").call(this);
            }
            this.list = this.querySelector(".list");
            this.breadcrumb = this.querySelector(".breadcrumb");
            this.uploadInput = this.querySelector("#upload-input");
            this.list.addEventListener("dblclick", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
            this.list.addEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_select, "f"));
            this.breadcrumb.addEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
            this.actions.addEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_handleActions, "f"));
            this.uploadInput.addEventListener("change", __classPrivateFieldGet(this, _EdenFileManager_handleUpload, "f"));
        });
        _EdenFileManager_loadImages.set(this, async () => {
            const images = Array.from(this.querySelectorAll("[data-image][data-path]"));
            for await (const image of images) {
                const source = image.querySelector("img")?.getAttribute("data-src");
                if (source) {
                    await __classPrivateFieldGet(this, _EdenFileManager_preloadImage, "f").call(this, source);
                }
                const element = image.querySelector("img");
                if (element && source) {
                    element.setAttribute("src", source);
                    element.removeAttribute("data-src");
                    image.removeAttribute("data-loading");
                }
            }
        });
        _EdenFileManager_preloadImage.set(this, async (src) => {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.onload = () => resolve(img.height);
                img.onerror = reject;
                img.src = src;
            });
        });
        _EdenFileManager_loadFiles.set(this, async () => {
            __classPrivateFieldGet(this, _EdenFileManager_spawnLoader, "f").call(this);
            const { files, storage } = await loadFileManagerData(this.currentPath);
            this.files = files;
            this.storage = storage;
            if (!__classPrivateFieldGet(this, _EdenFileManager_isMounted, "f")) {
                __classPrivateFieldGet(this, _EdenFileManager_destroyLoader, "f").call(this);
                return;
            }
            __classPrivateFieldGet(this, _EdenFileManager_render, "f").call(this, this.files, this.storage);
        });
        _EdenFileManager_navigate.set(this, async (e) => {
            const target = e.target;
            if (!target)
                return;
            const folderTarget = target.closest("[data-folder][data-path]");
            const imageTarget = target.closest("[data-image][data-path]");
            if (!folderTarget && !imageTarget)
                return;
            if (folderTarget && folderTarget.dataset.path) {
                this.currentPath = folderTarget.dataset.path;
                await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
            }
            if (imageTarget && this.uploadOnly && imageTarget.dataset.path) {
                const previewModal = new EdenModal({
                    icon: "image",
                    title: t("modals.file-manager.preview"),
                    content: imagePreviewTemplate(imageTarget.dataset.path),
                    fullScreen: true,
                });
                document.body.appendChild(previewModal);
            }
            if (imageTarget && !this.uploadOnly && imageTarget.dataset.path) {
                __classPrivateFieldGet(this, _EdenFileManager_openCropper, "f").call(this, imageTarget.dataset.path);
            }
        });
        _EdenFileManager_select.set(this, (e) => {
            const target = e.target;
            if (!target)
                return;
            const element = target.closest("[data-path]");
            if (!element) {
                this.selectedItem = null;
                const fileItems = Array.from(this.list.querySelectorAll(".list__item"));
                fileItems.forEach((item) => item.removeAttribute("data-selected"));
                __classPrivateFieldGet(this, _EdenFileManager_checkActions, "f").call(this);
                return;
            }
            const clickedPath = element.dataset.path;
            const { files = [] } = this.files;
            const matchingFile = files.find((file) => file.path === clickedPath);
            this.selectedItem =
                this.selectedItem?.path === matchingFile.path ? null : matchingFile;
            const fileItems = Array.from(this.list.querySelectorAll(".list__item"));
            fileItems.forEach((item) => {
                if (!this.selectedItem) {
                    return item.removeAttribute("data-selected");
                }
                const path = item.dataset.path;
                if (path === this.selectedItem.path) {
                    item.setAttribute("data-selected", "");
                }
                else {
                    item.removeAttribute("data-selected");
                }
            });
            __classPrivateFieldGet(this, _EdenFileManager_checkActions, "f").call(this);
        });
        _EdenFileManager_openCropper.set(this, (path) => {
            if (!this.width || !this.height) {
                snackbar(t("snackbars.missing-crop-dimensions"), "error");
                return;
            }
            const { edenApi, site } = window.EdenConfig;
            const imageSrc = buildFileManagerImageSrc(edenApi, site, path);
            const cropper = new EdenImageCropper({
                imageSrc,
                targetWidth: this.width,
                targetHeight: this.height,
                metadata: this.metadata,
                onCrop: async (cropData) => {
                    const { x, y, width, height } = cropData;
                    const { file } = await cropItem(path, x, y, width, height, this.width, this.height);
                    if (file) {
                        const url = __classPrivateFieldGet(this, _EdenFileManager_assetsUrl, "f").concat(file);
                        const metadata = encodeFileManagerCropMetadata({
                            path,
                            x,
                            y,
                            width,
                            height,
                        });
                        this.callback(url, metadata);
                    }
                },
            });
            const cropperModal = new EdenModal({
                icon: "image",
                title: `${t("modals.file-manager.crop-title")} ${this.width}x${this.height}`,
                content: cropper,
                noPadding: true,
                fullScreen: true,
                onClose: () => {
                    const fileManagerModal = document.getElementById("eden-file-manager-modal");
                    if (this.metadata && fileManagerModal) {
                        fileManagerModal.close();
                    }
                },
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.confirm"),
                        onClick: async () => {
                            await cropper.onConfirm();
                            snackbar(t("snackbars.image-cropped"), "success");
                        },
                        cssClass: "confirm",
                    },
                ],
            });
            document.body.appendChild(cropperModal);
        });
        _EdenFileManager_goHome.set(this, async () => {
            this.currentPath = "/";
            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
        });
        _EdenFileManager_goBack.set(this, async () => {
            const previousPath = resolvePreviousBreadcrumbPath(this.files?.breadcrumb);
            if (!previousPath)
                return;
            this.currentPath = previousPath;
            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
        });
        _EdenFileManager_removeItem.set(this, () => {
            if (!this.selectedItem)
                return;
            const { name, path } = this.selectedItem;
            const modal = new EdenModal({
                icon: "delete",
                title: t("modals.file-manager.remove-element"),
                content: `${t("modals.file-manager.remove-confirm")} "${name}" ?`,
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.remove"),
                        onClick: async () => {
                            await removeItem(this.currentPath, [path]);
                            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
                            snackbar(t("snackbars.element-removed"), "success");
                        },
                        cssClass: "confirm",
                        autofocus: true,
                    },
                ],
                closeButton: false,
            });
            document.body.appendChild(modal);
        });
        _EdenFileManager_addFolder.set(this, () => {
            const modal = new EdenModal({
                icon: "add_folder",
                title: t("modals.file-manager.create-folder"),
                width: 420,
                content: html `<eden-input
        type="text"
        label="${t("modals.file-manager.folder-name")}"
        name="label"
        autofocus=""
      ></eden-input>`,
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.confirm"),
                        onClick: async (currentModal) => {
                            if (!currentModal)
                                return;
                            const root = currentModal.shadowRoot;
                            const input = root.querySelector("eden-input");
                            const value = input.value;
                            await createFolder(value, this.currentPath);
                            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
                            snackbar(t("snackbars.folder-created"), "success");
                            currentModal.close();
                        },
                        cssClass: "confirm",
                        keepOpened: true,
                    },
                ],
            });
            document.body.appendChild(modal);
        });
        _EdenFileManager_renameItem.set(this, () => {
            if (!this.selectedItem)
                return;
            const { name, path } = this.selectedItem;
            const modal = new EdenModal({
                icon: "edit_pen",
                title: t("modals.file-manager.rename-element"),
                width: 420,
                content: html `<eden-input
        type="text"
        label="${t("modals.file-manager.element-name")}"
        name="label"
        value="${name}"
        autofocus=""
      ></eden-input>`,
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.confirm"),
                        onClick: async (currentModal) => {
                            if (!currentModal)
                                return;
                            const root = currentModal.shadowRoot;
                            const input = root.querySelector("eden-input");
                            const value = input.getAttribute("value") || "";
                            await renameItem(path, value);
                            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
                            snackbar(t("snackbars.element-renamed"), "success");
                            currentModal.close();
                        },
                        cssClass: "confirm",
                        keepOpened: true,
                    },
                ],
            });
            document.body.appendChild(modal);
        });
        _EdenFileManager_rotateImage.set(this, async () => {
            if (!this.selectedItem)
                return;
            const { edenApi } = window.EdenConfig;
            const { path, thumb } = this.selectedItem;
            const rotateButton = this.actions.querySelector("[data-action='rotate']");
            if (rotateButton) {
                rotateButton.setAttribute("disabled", "");
            }
            await rotateImage(path);
            const target = this.list.querySelector(`[data-path="${path}"] img`);
            const rand = crypto.randomUUID();
            const thumbnail = edenApi.concat(thumb, "?r=", rand);
            if (target) {
                target.setAttribute("src", thumbnail);
            }
            snackbar(t("snackbars.rotate-done"), "success");
            if (rotateButton) {
                rotateButton.removeAttribute("disabled");
            }
        });
        _EdenFileManager_moveItem.set(this, async () => {
            if (!this.selectedItem)
                return;
            let root = null;
            let selectedPath = null;
            const list = await moveList([this.selectedItem.path]);
            const navTree = new EdenStructureTree({
                tree: [list],
                linking: true,
                depth: 0,
            });
            const nodeClicked = (e) => {
                const customEvent = e;
                const node = customEvent.detail;
                if (!node || !root)
                    return;
                const path = node.dataset.path;
                node.setAttribute("selected", "");
                Array.from(root.querySelectorAll("eden-structure-tree-node")).forEach((el) => {
                    if (el !== node && el.hasAttribute("selected"))
                        el.removeAttribute("selected");
                });
                if (path) {
                    selectedPath = path;
                }
            };
            const confirm = async () => {
                if (!this.selectedItem || !selectedPath)
                    return;
                await moveItem(this.currentPath, [this.selectedItem.path], selectedPath);
                await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
                snackbar(t("snackbars.element-moved"), "success");
            };
            const moveSelector = Object.assign(document.createElement("div"), {
                className: "move-selector",
                innerHTML: html `<style>
        .move-selector {
          flex: 1 1 100%;
          display: flex;
          flex-direction: column;
        }

        .move-selector > eden-structure-tree {
          flex: 1 1 100%;
        }

        ${structureTreeStyles(".move-selector")}
      </style>`,
            });
            const modal = new EdenModal({
                icon: "tree",
                title: t("modals.file-manager.select-destination"),
                width: 420,
                height: 500,
                content: moveSelector,
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.validate"),
                        onClick: confirm,
                        cssClass: "confirm",
                    },
                ],
                noPadding: true,
            });
            document.body.appendChild(modal);
            root = modal.shadowRoot;
            const container = root.querySelector(".move-selector");
            if (container) {
                container.appendChild(navTree);
            }
            const nodesToOpen = Array.from(root.querySelectorAll(".move-selector eden-structure-tree-node"));
            root.addEventListener(EdenEvents.structureNodeClicked, nodeClicked);
            nodesToOpen.forEach((node) => node.openNode());
        });
        _EdenFileManager_handleUpload.set(this, async () => {
            if (!this.currentPath)
                return;
            const { site } = window.EdenConfig;
            const files = this.uploadInput.files;
            if (!files || files.length === 0)
                return;
            __classPrivateFieldGet(this, _EdenFileManager_spawnLoader, "f").call(this);
            await uploadFilesToCurrentPath({
                site,
                currentPath: this.currentPath,
                files,
            });
            __classPrivateFieldGet(this, _EdenFileManager_destroyLoader, "f").call(this);
            snackbar(t("snackbars.files-uploaded"), "success");
            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
        });
        _EdenFileManager_handleActions.set(this, async (e) => {
            const target = e.target;
            if (!target)
                return;
            const button = target.closest("[data-action]");
            if (!button)
                return;
            const action = button.dataset.action;
            if (!action)
                return;
            await dispatchFileManagerAction(action, {
                goBack: __classPrivateFieldGet(this, _EdenFileManager_goBack, "f"),
                goHome: __classPrivateFieldGet(this, _EdenFileManager_goHome, "f"),
                addFolder: __classPrivateFieldGet(this, _EdenFileManager_addFolder, "f"),
                moveItem: __classPrivateFieldGet(this, _EdenFileManager_moveItem, "f"),
                removeItem: __classPrivateFieldGet(this, _EdenFileManager_removeItem, "f"),
                renameItem: __classPrivateFieldGet(this, _EdenFileManager_renameItem, "f"),
                rotateImage: __classPrivateFieldGet(this, _EdenFileManager_rotateImage, "f"),
                selectCurrentItem: () => {
                    if (!this.selectedItem)
                        return;
                    __classPrivateFieldGet(this, _EdenFileManager_openCropper, "f").call(this, this.selectedItem.path);
                },
                triggerFileUpload: () => this.uploadInput.click(),
            });
        });
        _EdenFileManager_checkActions.set(this, () => {
            const { allowControls = false } = this.files || {};
            const renameButton = this.actions.querySelector("[data-action='rename']");
            const moveButton = this.actions.querySelector("[data-action='move']");
            const optimizeButton = this.actions.querySelector("[data-action='optimize']");
            const rotateButton = this.actions.querySelector("[data-action='rotate']");
            const removeButton = this.actions.querySelector("[data-action='remove']");
            const selectButton = this.actions.querySelector("[data-action='select']");
            const uploadButton = this.actions.querySelector("[data-action='file-upload']");
            if (allowControls && this.selectedItem) {
                renameButton.removeAttribute("disabled");
                moveButton.removeAttribute("disabled");
                removeButton.removeAttribute("disabled");
            }
            else {
                renameButton.setAttribute("disabled", "");
                moveButton.setAttribute("disabled", "");
                removeButton.setAttribute("disabled", "");
            }
            if (allowControls && this.storage.ratio < 100) {
                uploadButton.removeAttribute("disabled");
            }
            else {
                uploadButton.setAttribute("disabled", "");
            }
            if (allowControls && this.selectedItem?.kind === "file") {
                optimizeButton.removeAttribute("disabled");
                rotateButton.removeAttribute("disabled");
            }
            else {
                optimizeButton.setAttribute("disabled", "");
                rotateButton.setAttribute("disabled", "");
            }
            if (allowControls &&
                !this.uploadOnly &&
                this.selectedItem?.kind === "file") {
                selectButton?.removeAttribute("disabled");
            }
            else {
                selectButton?.setAttribute("disabled", "");
            }
        });
        _EdenFileManager_spawnLoader.set(this, () => {
            this.loader = Object.assign(document.createElement("div"), {
                className: "loader",
            });
            this.appendChild(this.loader);
        });
        _EdenFileManager_destroyLoader.set(this, () => {
            if (!this.loader)
                return;
            this.loader.remove();
            this.loader = null;
        });
        _EdenFileManager_initialize.set(this, async (token) => {
            await __classPrivateFieldGet(this, _EdenFileManager_loadFiles, "f").call(this);
            if (!__classPrivateFieldGet(this, _EdenFileManager_isMounted, "f") || token !== __classPrivateFieldGet(this, _EdenFileManager_initToken, "f")) {
                return;
            }
            if (this.metadata?.path) {
                try {
                    __classPrivateFieldGet(this, _EdenFileManager_openCropper, "f").call(this, this.metadata.path);
                }
                catch {
                    snackbar(t("snackbars.previous-image-not-found"), "error");
                }
            }
        });
        this.modal = modal;
        this.callback = callback;
        this.width = width;
        this.height = height;
        this.uploadOnly = uploadOnly;
        this.bareMetadata = metadata;
        this.metadata = parseFileManagerMetadata(this.bareMetadata);
        this.currentPath = "/";
        this.selectedItem = null;
        this.loader = null;
        __classPrivateFieldGet(this, _EdenFileManager_render, "f").call(this);
    }
    connectedCallback() {
        var _a;
        __classPrivateFieldSet(this, _EdenFileManager_isMounted, true, "f");
        const token = __classPrivateFieldSet(this, _EdenFileManager_initToken, (_a = __classPrivateFieldGet(this, _EdenFileManager_initToken, "f"), ++_a), "f");
        void __classPrivateFieldGet(this, _EdenFileManager_initialize, "f").call(this, token);
    }
    disconnectedCallback() {
        __classPrivateFieldSet(this, _EdenFileManager_isMounted, false, "f");
        __classPrivateFieldSet(this, _EdenFileManager_initToken, __classPrivateFieldGet(this, _EdenFileManager_initToken, "f") + 1, "f");
        this.actions?.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_handleActions, "f"));
        this.breadcrumb?.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
        this.list?.removeEventListener("click", __classPrivateFieldGet(this, _EdenFileManager_select, "f"));
        this.list?.removeEventListener("dblclick", __classPrivateFieldGet(this, _EdenFileManager_navigate, "f"));
        this.uploadInput?.removeEventListener("change", __classPrivateFieldGet(this, _EdenFileManager_handleUpload, "f"));
    }
}
_EdenFileManager_assetsUrl = new WeakMap(), _EdenFileManager_isMounted = new WeakMap(), _EdenFileManager_initToken = new WeakMap(), _EdenFileManager_render = new WeakMap(), _EdenFileManager_loadImages = new WeakMap(), _EdenFileManager_preloadImage = new WeakMap(), _EdenFileManager_loadFiles = new WeakMap(), _EdenFileManager_navigate = new WeakMap(), _EdenFileManager_select = new WeakMap(), _EdenFileManager_openCropper = new WeakMap(), _EdenFileManager_goHome = new WeakMap(), _EdenFileManager_goBack = new WeakMap(), _EdenFileManager_removeItem = new WeakMap(), _EdenFileManager_addFolder = new WeakMap(), _EdenFileManager_renameItem = new WeakMap(), _EdenFileManager_rotateImage = new WeakMap(), _EdenFileManager_moveItem = new WeakMap(), _EdenFileManager_handleUpload = new WeakMap(), _EdenFileManager_handleActions = new WeakMap(), _EdenFileManager_checkActions = new WeakMap(), _EdenFileManager_spawnLoader = new WeakMap(), _EdenFileManager_destroyLoader = new WeakMap(), _EdenFileManager_initialize = new WeakMap();
export default EdenFileManager;
if (!customElements.get("eden-file-manager")) {
    customElements.define("eden-file-manager", EdenFileManager);
}
