package de.gecheckt.pdf.umbenenner.adapter.in.gui;

import de.gecheckt.pdf.umbenenner.adapter.in.gui.editor.GuiChangeState;
import de.gecheckt.pdf.umbenenner.adapter.in.gui.editor.GuiConfigurationEditorState;

/**
 * Formats the window title string for the PDF-Umbenenner GUI editor.
 * <p>
 * The title reflects the current editor state: whether a file is loaded and whether the
 * editor contains unsaved changes. The application name and the separator are kept in
 * one place so every part of the GUI uses the same formatting convention.
 *
 * <ul>
 *   <li>Clean state with loaded file: {@code "PDF-Umbenenner — <filename>"}</li>
 *   <li>Clean state without file (new configuration): {@code "PDF-Umbenenner — Neue Konfiguration"}</li>
 *   <li>Dirty state: the same formats with a leading {@code "* "} prefix</li>
 * </ul>
 */
public final class GuiWindowTitleFormatter {

    /** The application name shown in every window title variant. */
    static final String APPLICATION_NAME = "PDF-Umbenenner";

    /** Separator placed between the application name and the context section. */
    static final String SEPARATOR = " \u2014 ";

    /** Prefix added to the title when the editor contains unsaved changes. */
    static final String DIRTY_PREFIX = "* ";

    /** Context label used when no file has been loaded yet. */
    static final String NEW_CONFIGURATION_LABEL = "Neue Konfiguration";

    private GuiWindowTitleFormatter() {
        // Utility class.
    }

    /**
     * Formats the window title for the given editor state.
     *
     * @param editorState the current editor state; must not be {@code null}
     * @return the formatted window title string; never {@code null}
     */
    public static String format(GuiConfigurationEditorState editorState) {
        String contextPart = buildContextPart(editorState);
        String base = APPLICATION_NAME + SEPARATOR + contextPart;
        if (editorState.changeState() == GuiChangeState.DIRTY) {
            return DIRTY_PREFIX + base;
        }
        return base;
    }

    /**
     * Returns the context portion of the title (the part after the separator).
     *
     * @param editorState the current editor state; must not be {@code null}
     * @return the context string; never {@code null}
     */
    private static String buildContextPart(GuiConfigurationEditorState editorState) {
        if (editorState.isNewConfiguration()) {
            return NEW_CONFIGURATION_LABEL;
        }
        String fullPath = editorState.loadedFileSnapshot()
                .map(snapshot -> snapshot.filePath().getFileName())
                .map(Object::toString)
                .orElse(NEW_CONFIGURATION_LABEL);
        return fullPath;
    }
}
