import {
    errorDialogOpen,
    openChangeFontSizeDialog,
    openChangeThemeDialog,
    openErrorDialog,
    openSaveFilesDialog
} from "./dialogs.js";
import {languagesStrings, setUserLanguage, setWebsiteContentInUserLanguage, userLanguage} from "./language.js";
import {loadCodeFile, loadTerritoryFile} from "./saveAndLoad.js";
import {disableAutoCompletion, enableAutoCompletion, replaceStartText} from "./cmEditor.js";

let menuOpen;
let dropdownMenuOpen;
let languageDropdownMenuOpen;
let menu;
let hamburgerBtn;
let dropdownMenuButton;
let languageDropdownMenuButton;
let editorSettingsDropdown;
let changeLanguageDropdown;
let languageGermanRadioButton;
let languageEnglishRadioButton;

/**
 * Initialisiert die Funktionen des Hamburger-Menüs.
 */
export function initMenu() {
    menuOpen = false;
    dropdownMenuOpen = false;
    languageDropdownMenuOpen = false;

    hamburgerBtn = document.getElementById('burger-button');
    menu = document.getElementById('menu');
    const editorSettingsLink = document.getElementById('editor-settings');
    const changeLanguageLink = document.getElementById('change-language');
    editorSettingsDropdown = document.getElementById('editor-settings-dropdown');
    changeLanguageDropdown = document.getElementById('change-language-dropdown');
    const autoCompletionLink = document.getElementById('auto-completion-link');
    const autoCompletionCheckbox = document.getElementById('auto-completion-checkbox');
    const languageGermanLink = document.getElementById('language-german-link');
    languageGermanRadioButton = document.getElementById('language-german-radio-button');
    const languageEnglishLink = document.getElementById('language-english-link');
    languageEnglishRadioButton = document.getElementById('language-english-radio-button');
    dropdownMenuButton = document.getElementById('dropdown-menu-button');
    languageDropdownMenuButton = document.getElementById('language-dropdown-menu-button');
    const changeFontSizeLink = document.getElementById('change-font-size');
    const changeThemeLink = document.getElementById('change-theme');

    setLanguageRadioButton();

    hamburgerBtn.addEventListener('click', function (event) {
        event.preventDefault();
        toggleMenu(event);
    });
    
    editorSettingsLink.addEventListener('click', function(event) {
        event.preventDefault();
        hamburgerBtn.focus();
        editorSettingsDropdown.classList.toggle('hidden');
        editorSettingsDropdown.classList.toggle('flex');
        toggleDropdownMenuAnimation(dropdownMenuButton);
        dropdownMenuOpen = !dropdownMenuOpen;
    });

    autoCompletionLink.addEventListener('click', function(event) {
        event.preventDefault();
        autoCompletionCheckbox.click();
    });

    autoCompletionCheckbox.addEventListener('change', function() {
        if (autoCompletionCheckbox.checked) {
            enableAutoCompletion();
        } else {
            disableAutoCompletion();
        }
    });

    changeFontSizeLink.addEventListener('click', function(event) {
        event.preventDefault();
        openChangeFontSizeDialog();
    });

    changeThemeLink.addEventListener('click', function(event) {
        event.preventDefault();
        openChangeThemeDialog();
    });

    changeLanguageLink.addEventListener('click', function(event) {
        event.preventDefault();
        hamburgerBtn.focus();
        changeLanguageDropdown.classList.toggle('hidden');
        changeLanguageDropdown.classList.toggle('flex');
        toggleDropdownMenuAnimation(languageDropdownMenuButton);
        languageDropdownMenuOpen = !languageDropdownMenuOpen;
    });

    languageGermanLink.addEventListener('click', function(event) {
        event.preventDefault();
        languageGermanRadioButton.click();
    });

    languageGermanRadioButton.addEventListener('change', function (event) {
        event.preventDefault();
        setUserLanguage('de');
        setWebsiteContentInUserLanguage();
        replaceStartText();
    });

    languageEnglishLink.addEventListener('click', function(event) {
        event.preventDefault();
        languageEnglishRadioButton.click();
    });

    languageEnglishRadioButton.addEventListener('change', function (event) {
        event.preventDefault();
        setUserLanguage('en');
        setWebsiteContentInUserLanguage();
        replaceStartText();
    });

    document.getElementById('save-Files').addEventListener('click', openSaveFilesDialog);
    document.getElementById('load-Files').addEventListener('click', function (event) {
        event.preventDefault();
        document.getElementById('file-upload').click();
    });

    document.getElementById('file-upload').addEventListener('change', handleFileUploadChange);
}

/**
 * Verwaltet den Upload von Hamster-Programmen und Territorium-Dateien.
 *
 * @param event, das auslösende Event.
 */
function handleFileUploadChange(event) {
    event.preventDefault();

    const fileInput = document.getElementById('file-upload');
    const file = event.target.files[0];

    if (file) {
        // Versuche Datei als Hamster-Programm oder Territorium-Datei zu laden
        loadTerritoryFile(event, file, function(territoryLoaded) {
            if (!territoryLoaded) {
                loadCodeFile(event, file, function(codeLoaded) {
                    if (!codeLoaded && !errorDialogOpen) {
                        openErrorDialog(languagesStrings[userLanguage]['error-file']);
                    }
                });
            }
        });

        // Setze den Wert des Datei-Eingabefelds zurück, um das Event erneut auszulösen
        fileInput.value = "";
    }
}

/**
 * Setzt den Radio-Button des Sprachmenüs entsprechend der geladenen Sprache der Webseite.
 */
function setLanguageRadioButton() {
    switch (userLanguage) {
        case "de":
            languageGermanRadioButton.click();
            return;
        case "en":
            languageEnglishRadioButton.click();
            return;
    }
}

/**
 * Transformiert das Aussehen des Burger-Menü-Buttons.
 * Beim Öffnen des Hauptmenüs entsteht ein "X", beim Schließen das Standard-Design eines Burger-Menüs.
 */
function transformBurgerMenu() {
    let burgerMenuSpan1 = document.getElementById('burger-menu-1');
    let burgerMenuSpan2 = document.getElementById('burger-menu-2');
    let burgerMenuSpan3 = document.getElementById('burger-menu-3');
    let burgerMenuSpan4 = document.getElementById('burger-menu-4');
    let burgerMenuSpan5 = document.getElementById('burger-menu-5');
    let burgerMenuSpan6 = document.getElementById('burger-menu-6');
    let burgerMenuSpan7 = document.getElementById('burger-menu-7');

    burgerMenuSpan1.classList.toggle('ring-0')
    burgerMenuSpan1.classList.toggle('ring-4')
    burgerMenuSpan2.classList.toggle('translate-x-20')
    burgerMenuSpan3.classList.toggle('translate-x-20')
    burgerMenuSpan4.classList.toggle('translate-x-20')
    burgerMenuSpan5.classList.toggle('-translate-x-20')
    burgerMenuSpan5.classList.toggle('translate-x-0')
    burgerMenuSpan5.classList.toggle('w-12')
    burgerMenuSpan6.classList.toggle('rotate-0')
    burgerMenuSpan6.classList.toggle('rotate-45')
    burgerMenuSpan7.classList.toggle('-rotate-0')
    burgerMenuSpan7.classList.toggle('-rotate-45')
}

/**
 * Öffnet das Hauptmenü und macht es sichtbar.
 */
export function openMenu() {
    transformBurgerMenu();
    
    if (menu.classList.contains('hidden')) {
        menu.classList.remove('hidden');
        menu.classList.add('flex');
    }

    menuOpen = true;
}

/**
 * Schließt das Hauptmenü und versteckt es.
 * Falls das auslösende Event die Checkbox oder das Element zum Ein-/Ausschalten der automatischen Textvervollständigung
 * oder das Element zum Anzeigen des Texteditor-Einstellungen-Untermenüs ist, bleibt das Hauptmenü geöffnet.
 * 
 * @param event, das auslösende Event.
 */
export function closeMenu(event) {
    if (event.target !== undefined &&
        (event.target.id === 'auto-completion-checkbox' ||
            event.target.id === 'auto-completion-link' ||
            event.target.id === 'editor-settings' ||
            event.target.id === 'menu')) {
        return;
    }

    if (menu.classList.contains('flex')) {
        menu.classList.remove('flex');
        menu.classList.add('hidden');
    }

    transformBurgerMenu();
    menuOpen = false;
    hideSubMenus();
}

/**
 * Triggert das Öffnen und Schließen des Hauptmenüs.
 * 
 * @param event, das auslösende Event.
 */
function toggleMenu(event) {
    if (menuOpen) {
        closeMenu(event);
    } else {
        openMenu();
    }
}

/**
 * Triggert die Animation des Texteditor-Einstellungen-Untermenüs.
 */
function toggleDropdownMenuAnimation(element) {
    element.classList.toggle('transition');
    element.classList.toggle('duration-300');
    element.classList.toggle('rotate-90');
    element.classList.toggle('ease-in-out');
}

/**
 * Blendet das Untermenü der Texteditor-Einstellungen aus.
 */
function hideSubMenus() {
    if (editorSettingsDropdown.classList.contains('flex')) {
        editorSettingsDropdown.classList.remove('flex');
        editorSettingsDropdown.classList.add('hidden');
    }

    if (dropdownMenuOpen) {
        toggleDropdownMenuAnimation(dropdownMenuButton);
        dropdownMenuOpen = false;
    }

    if (changeLanguageDropdown.classList.contains('flex')) {
        changeLanguageDropdown.classList.remove('flex');
        changeLanguageDropdown.classList.add('hidden');
    }

    if (languageDropdownMenuOpen) {
        toggleDropdownMenuAnimation(languageDropdownMenuButton);
        languageDropdownMenuOpen = false;
    }
}