"""
Handles application settings and configuration
"""

from .config_handler import save_config
from PySide6.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QFileDialog,
    QDialogButtonBox,
    QMessageBox,
)
from pathlib import Path
import os
import subprocess
import shutil
import sys


class SettingsManager:
    def __init__(self, parent):
        self.parent = parent

    def show_settings_dialog(self):
        """Show settings dialog to configure chdman path"""
        dialog = QDialog(self.parent)
        dialog.setWindowTitle("Settings")
        layout = QVBoxLayout()

        # Path input
        path_layout = QHBoxLayout()
        path_label = QLabel("chdman Path:")
        self.path_edit = QLineEdit(self.parent.config.get("chdman_path", ""))
        browse_button = QPushButton("Browse...")

        def browse():
            path, _ = QFileDialog.getOpenFileName(
                self.parent,
                "Select chdman executable",
                str(Path.home()),
                "Executable files (*.exe);;All files (*.*)",
            )
            if path:
                self.path_edit.setText(path)

        browse_button.clicked.connect(browse)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_edit)
        path_layout.addWidget(browse_button)
        layout.addLayout(path_layout)

        # Buttons
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(lambda: self.save_settings(dialog))
        button_box.rejected.connect(dialog.reject)
        layout.addWidget(button_box)

        dialog.setLayout(layout)
        dialog.exec()

    def save_settings(self, dialog):
        """Save settings from dialog"""
        self.parent.config["chdman_path"] = self.path_edit.text()
        if save_config(self.parent.config):
            dialog.accept()
            self.parent.check_chdman()  # Re-check with new path
        else:
            QMessageBox.warning(self.parent, "Error", "Failed to save settings")

    def check_chdman(self):
        """Check if chdman is available in the path"""
        try:
            chdman_name = "chdman.exe" if sys.platform == "win32" else "chdman"
            chdman_path = shutil.which(chdman_name)

            if chdman_path:
                self.parent.config["chdman_path"] = chdman_path
                save_config(self.parent.config)
                self.parent.statusBar().showMessage(f"Found chdman at {chdman_path}")
            else:
                raise FileNotFoundError()
        except FileNotFoundError:
            self.handle_chdman_not_found()

    def handle_chdman_not_found(self):
        """Handle case when chdman is not found"""
        QMessageBox.critical(
            self.parent, "Error", "chdman not found in PATH. Please install MAME tools."
        )
        self.parent.statusBar().showMessage("chdman not found!")
        self.offer_platform_specific_download()

    def offer_platform_specific_download(self):
        """Offer platform-specific download options"""
        if sys.platform == "win32":
            reply = QMessageBox.question(
                self.parent,
                "Download MAME?",
                "Would you like to download the latest version of MAME?\
                (Once Windows binaries are downloaded/extracted place chdman.exe in the same folder as this program)",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            )
            if reply == QMessageBox.StandardButton.Yes:
                import webbrowser

                webbrowser.open("https://www.mamedev.org/release.html")
        elif sys.platform == "darwin":  # Mac
            reply = QMessageBox.question(
                self.parent,
                "Install rom-tools?",
                "Would you like to install rom-tools via Homebrew?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            )
            if reply == QMessageBox.StandardButton.Yes:
                import webbrowser

                webbrowser.open("https://formulae.brew.sh/formula/rom-tools")
        elif sys.platform.startswith("linux"):
            reply = QMessageBox.question(
                self.parent,
                "Install mame-tools?",
                "Would you like to install mame-tools for your distribution?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            )
            if reply == QMessageBox.StandardButton.Yes:
                import webbrowser

                webbrowser.open("https://pkgs.org/download/mame-tools")
