/*
 * Copyright (C) 2025-2026  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.ui.theme;

import org.aglais.zms.util.Log;
import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;

/**
 * Abstract class for detecting the operating system's theme (dark/light mode).
 * Provides functionality to register listeners that will be notified when the theme changes.
 */
public abstract class OSThemeDetector implements Runnable {

    private static final String LOG_TAG = OSThemeDetector.class.getSimpleName();
    private static final OSThemeDetector INSTANCE = createInstance();

    private final ExecutorService detectorExecutor = Executors.newSingleThreadExecutor();
    private Future<?> detectorFuture;
    protected final Set<Consumer<Boolean>> listeners = new HashSet<>();

    /**
     * Creates an appropriate instance of OSThemeDetector based on the operating system.
     *
     * @return An instance of OSThemeDetector specific to the current operating system
     */
    private static OSThemeDetector createInstance() {
        String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
        if (os.startsWith("linux")) {
            String desktop = System.getenv("XDG_CURRENT_DESKTOP");
            if ("GNOME".equalsIgnoreCase(desktop)) {
                return new LinuxGNOMEOSThemeDetector();
            } else if ("KDE".equalsIgnoreCase(desktop)) {
                return new LinuxKDEOSThemeDetector();
            } else {
                Log.e(LOG_TAG, "Linux with unsupported desktop environment \"" + desktop + "\"");
            }
        } else if (os.startsWith("windows")) {
            return new WindowsOSThemeDetector();
        } else {
            Log.e(LOG_TAG, "Unsupported OS \"" + os + "\"");
        }

        return new OSThemeDetector() {
            @Override
            public void run() {
                // Default implementation does nothing
            }

            @Override
            public boolean isDark() {
                return false;
            }
        };
    }

    /**
     * Gets the singleton instance of OSThemeDetector.
     *
     * @return The singleton instance of OSThemeDetector
     */
    public static OSThemeDetector getInstance() {
        return INSTANCE;
    }

    /**
     * Checks if the current OS theme is dark mode.
     *
     * @return true if the theme is dark, false if light
     */
    public abstract boolean isDark();

    /**
     * Registers a listener to be notified when the theme changes.
     *
     * @param listener The listener to be notified, receives a boolean (true for dark mode)
     */
    public void registerListener(@NotNull Consumer<Boolean> listener) {
        listeners.add(listener);

        if (detectorFuture == null) {
            detectorFuture = detectorExecutor.submit(this);
        }
    }

    /**
     * Unregisters a previously registered theme change listener.
     *
     * @param listener The listener to be removed
     */
    public void unregisterListener(@NotNull Consumer<Boolean> listener) {
        listeners.remove(listener);

        if (listeners.isEmpty() && detectorFuture != null) {
            detectorFuture.cancel(true);
            detectorFuture = null;
        }
    }
}