import os

from qgis.PyQt import QtWidgets
from qgis.core import QgsApplication

from ..compatibility_routines import QT_BUTTON_BOX_OK, QT_BUTTON_BOX_CANCEL


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.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)

    @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)
