from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QRadioButton, QSizePolicy, QSpacerItem, QVBoxLayout

from .classes.basemaps import BaseMaps
from .classes.settings import Settings
from .compat import DLGBTN_APPLY, DLGBTN_CANCEL, DLGBTN_RESET, DLGBTN_ROLE_APPLY, DLGBTN_ROLE_RESET, HORIZONTAL, SPSZ_EXPANDING, SPSZ_FIXED, SPSZ_MINIMUM, SPSZ_MINIMUM_EXPANDING


class OptionsDialog(QDialog):
    closingPlugin = pyqtSignal()
    dataChange = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor."""
        QDialog.__init__(self, parent)
        self.setupUi()
        self.setWindowTitle("Riverscapes Viewer Settings")

        self.basemaps = BaseMaps()
        self.settings = Settings()
        self.buttonBox.clicked.connect(self.commit_settings)
        self.basemaps.load()
        self.setValues()

        self.regionHelp.setText(None)
        self.regionHelp.setIcon(QIcon(":/plugins/qrave_toolbar/Help.png"))
        self.regionHelp.setToolTip("Help choosing a basemap region")
        # self.regionHelp.clicked.connect(la
        self.regionHelp.setEnabled(False)

    def setValues(self):
        self.basemapsInclude.setChecked(self.settings.getValue("basemapsInclude"))
        self.loadDefaultView.setChecked(self.settings.getValue("loadDefaultView"))
        self.chk_telemetry.setChecked(self.settings.getValue("telemetryEnabled"))
        self.autoUpdate.setChecked(self.settings.getValue("autoUpdate"))
        self.txtBL.setText(self.settings.getValue("localBLFolder"))

        # Set the combo box
        self.basemapRegion.clear()
        region = self.settings.getValue("basemapRegion")
        self.basemapRegion.addItems(self.basemaps.regions.keys())
        if region and len(region) > 0:
            self.basemapRegion.setCurrentText(region)

        # Set the dock location radio buttons
        dock_location = self.settings.getValue("dockLocation")
        if dock_location == "left":
            self.left_radio.setChecked(True)
        elif dock_location == "right":
            self.right_radio.setChecked(True)
        else:
            self.left_radio.setChecked(True)  # Default

    def commit_settings(self, btn):
        role = self.buttonBox.buttonRole(btn)

        if role == DLGBTN_ROLE_APPLY:
            self.settings.setValue("basemapsInclude", self.basemapsInclude.isChecked())
            self.settings.setValue("loadDefaultView", self.loadDefaultView.isChecked())
            self.settings.setValue("telemetryEnabled", self.chk_telemetry.isChecked())
            self.settings.setValue("basemapRegion", self.basemapRegion.currentText())
            self.settings.setValue("autoUpdate", self.autoUpdate.isChecked())
            self.settings.setValue("localBLFolder", self.txtBL.text())
            if self.left_radio.isChecked():
                self.settings.setValue("dockLocation", "left")
            elif self.right_radio.isChecked():
                self.settings.setValue("dockLocation", "right")

        elif role == DLGBTN_ROLE_RESET:
            self.settings.resetAllSettings()
            self.setValues()

        # Emit a datachange so we can trigger other parts of this plugin
        self.dataChange.emit()

    def browseBLFolder(self):
        from qgis.PyQt.QtWidgets import QFileDialog

        folder = QFileDialog.getExistingDirectory(self, "Select Business Logic Folder", "")
        if folder and len(folder) > 0:
            self.txtBL.setText(folder)

    def setupUi(self):
        self.resize(365, 251)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        # Basemaps and region
        self.basemapsInclude = QCheckBox(self)
        self.verticalLayout.addWidget(self.basemapsInclude)
        self.basemapsInclude.setText("Include basemaps in explorer tree")
        self.horizontalLayout = QHBoxLayout()
        self.label = QLabel(self)
        self.label.setText("Region")
        self.horizontalLayout.addWidget(self.label)
        self.basemapRegion = QComboBox(self)
        sizePolicy = QSizePolicy(SPSZ_MINIMUM_EXPANDING, SPSZ_FIXED)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.basemapRegion.sizePolicy().hasHeightForWidth())
        self.basemapRegion.setSizePolicy(sizePolicy)
        self.horizontalLayout.addWidget(self.basemapRegion)
        self.regionHelp = QPushButton(self)
        self.horizontalLayout.addWidget(self.regionHelp)
        self.verticalLayout.addLayout(self.horizontalLayout)
        # Auto Update Checkbox
        self.autoUpdate = QCheckBox(self)
        self.autoUpdate.setText("Automatically update resource files (symbology, business logic etc.)")
        self.verticalLayout.addWidget(self.autoUpdate)
        # Load Default View Checkbox
        self.loadDefaultView = QCheckBox(self)
        self.loadDefaultView.setText("Load default project views when opening projects")
        self.verticalLayout.addWidget(self.loadDefaultView)

        # Telemetry
        self.chk_telemetry = QCheckBox("Help improve the software by sharing anonymous usage data.")
        self.verticalLayout.addWidget(self.chk_telemetry)

        # Dock location radio buttons
        self.grid = QGridLayout()
        self.labelDock = QLabel("Default Dock widget location")
        self.grid.addWidget(self.labelDock, 0, 0, 1, 2)
        self.left_radio = QRadioButton("Dock to left")
        self.right_radio = QRadioButton("Dock to right")
        self.grid.addWidget(self.left_radio, 1, 0)
        self.grid.addWidget(self.right_radio, 1, 1)
        self.verticalLayout.addLayout(self.grid)
        # Optional BL folder
        self.labelBL = QLabel("Local Business Logic Folder (Advanced Users)")
        self.verticalLayout.addWidget(self.labelBL)
        self.hlayout_bl = QHBoxLayout()
        self.txtBL = QLineEdit(self)
        self.txtBL.setReadOnly(True)
        self.hlayout_bl.addWidget(self.txtBL)
        self.btnBrowseBL = QPushButton("...")
        self.btnBrowseBL.clicked.connect(self.browseBLFolder)
        self.hlayout_bl.addWidget(self.btnBrowseBL)
        self.btnClearBL = QPushButton("Clear")
        self.btnClearBL.clicked.connect(lambda: self.txtBL.setText(""))
        self.hlayout_bl.addWidget(self.btnClearBL)
        self.verticalLayout.addLayout(self.hlayout_bl)
        # Button Box
        spacerItem = QSpacerItem(20, 154, SPSZ_MINIMUM, SPSZ_EXPANDING)
        self.verticalLayout.addItem(spacerItem)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(HORIZONTAL)
        self.buttonBox.setStandardButtons(DLGBTN_APPLY | DLGBTN_CANCEL | DLGBTN_RESET)
        self.verticalLayout.addWidget(self.buttonBox)
        # Standard buttons
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
