# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial

import sys
from typing import Optional

from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFormLayout,
                               QGroupBox, QVBoxLayout, QWidget)

from gui_utils import FilterPathChooser
from options import Options


class OptionsDialog(QDialog):
    """Options dialog letting the user choose the path to Qt Creator."""

    def __init__(self, parent: Optional[QWidget]):
        super(OptionsDialog, self).__init__(parent)
        self.setWindowTitle('Options')
        buttons = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self._dialogButtonBox = QDialogButtonBox(buttons)
        self._dialogButtonBox.rejected.connect(self.reject)
        self._dialogButtonBox.accepted.connect(self.accept)
        main_layout = QVBoxLayout(self)
        self._creator_group = QGroupBox('Qt Creator', self)
        self._creator_group.setCheckable(True)
        main_layout.addWidget(self._creator_group)
        form_layout = QFormLayout(self._creator_group)
        pattern = '*' if sys.platform != 'win32' else '*.exe'
        filters = [f'Executable ({pattern})']
        self._creator_chooser = FilterPathChooser('Path to Qt Creator',
                                                  filters, self)
        form_layout.addRow('Path:', self._creator_chooser)
        main_layout.addWidget(self._dialogButtonBox)

    def setVisible(self, visible: bool) -> None:
        """Overwrite QDialog.setVisible() to populate controls"""
        if visible:
            self._creator_group.setChecked(Options.use_creator())
            self._creator_chooser.set_path(Options.creator_path())
        super(OptionsDialog, self).setVisible(visible)

    def accept(self) -> None:
        """Overwrite QDialog.accept() to apply options values."""
        use_creator = self._creator_group.isChecked()
        creator_path = self._creator_chooser.path()
        if use_creator and not creator_path:
            self._creator_chooser.setFocus()
            return
        Options.set_use_creator(use_creator)
        Options.set_creator_path(creator_path)
        super(OptionsDialog, self).accept()
