import os
from pathlib import Path

from pyqt_compat import QtWidgets, QtGui

from pyqt_compat.compatibility_routines import QT_BUTTON_BOX_OK, QT_BUTTON_BOX_CANCEL

ICON_DIR = Path(__file__).parents[3] / 'icons/qgis'

class AddBinaryForm(QtWidgets.QDialog):

    def __init__(self, parent = None, key: str = '', value: str = ''):
        super().__init__(parent)
        self.setWindowTitle('Add TUFLOW binary')
        self.layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.layout)

        self.label1 = QtWidgets.QLabel('Version name')
        self.layout.addWidget(self.label1)
        self._version_name = QtWidgets.QLineEdit()
        self._version_name.setText(key)
        self.layout.addWidget(self._version_name)

        self.label2 = QtWidgets.QLabel('Path to TUFLOW binary')
        self.layout.addWidget(self.label2)
        self.location_layout = QtWidgets.QHBoxLayout()
        self._bin_location = QtWidgets.QLineEdit()
        self._bin_location.setText(value)
        self.location_layout.addWidget(self._bin_location)
        self.browse_btn = QtWidgets.QToolButton()
        #self.browse_btn.setIcon(QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.browse_btn.setIcon(self.icon('mActionFileOpen.svg'))
        self.browse_btn.clicked.connect(self.browse_btn_triggered)
        self.location_layout.addWidget(self.browse_btn)
        self.layout.addLayout(self.location_layout)

        self.button_box = QtWidgets.QDialogButtonBox(QT_BUTTON_BOX_OK | QT_BUTTON_BOX_CANCEL)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        self.layout.addWidget(self.button_box)

    @staticmethod
    def icon(name: str) -> QtGui.QIcon:
        icon_path = ICON_DIR / name
        if icon_path.exists():
            return QtGui.QIcon(str(icon_path))
        raise ValueError(f"Unable to load icon from: {icon_path}")
        return QtGui.QIcon()

    @property
    def version_name(self) -> str:
        return self._version_name.text()

    @property
    def bin_location(self) -> str:
        return self._bin_location.text()

    def browse_btn_triggered(self):
        ext = 'Executable files (*.exe);;All files (*)' if os.name == 'nt' else 'All files (*)'
        file = QtWidgets.QFileDialog.getOpenFileName(self, 'Select TUFLOW binary', '', ext)
        if file and file[0]:
            selected_file = file[0]
            self._bin_location.setText(selected_file)
