# -*- coding: utf-8 -*-
"""
/***************************************************************************
 OMRATMainWidget
                                 A QGIS plugin
 This is an open source implementation of Pedersens equations from 1995
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2022-12-22
        git sha              : $Format:%H$
        copyright            : (C) 2022 by Axel Hörteborn
        email                : axel.horteborn@ri.se
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os


from qgis.PyQt import QtGui, QtWidgets, uic
from qgis.PyQt.QtCore import Qt, pyqtSignal

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'omrat_base.ui'))


class OMRATMainWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, plugin=None, parent=None):
        """Constructor."""
        super(OMRATMainWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://doc.qt.io/qt-5/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.plugin = plugin
        self.is_active = True
        self._apply_visual_refresh()
        
        # Route tab
        self.twRouteList: QtWidgets.QTableWidget
        self.pbAddRoute: QtWidgets.QPushButton
        self.pbLoadRoute: QtWidgets.QPushButton
        self.pbRemoveRoute: QtWidgets.QPushButton
        self.pbStopRoute: QtWidgets.QPushButton
        self.pbUpdateAIS: QtWidgets.QPushButton
        self.laDir1:QtWidgets.QLabel
        self.laDir2:QtWidgets.QLabel
        self.pbStopRoute: QtWidgets.QPushButton
        self.leNormMean1_1: QtWidgets.QLineEdit
        self.leNormMean1_2: QtWidgets.QLineEdit
        self.leNormMean1_3: QtWidgets.QLineEdit
        self.leNormMean2_1: QtWidgets.QLineEdit
        self.leNormMean2_2: QtWidgets.QLineEdit
        self.leNormMean2_3: QtWidgets.QLineEdit
        self.leNormStd1_1: QtWidgets.QLineEdit
        self.leNormStd1_2: QtWidgets.QLineEdit
        self.leNormStd1_3: QtWidgets.QLineEdit
        self.leNormStd2_1: QtWidgets.QLineEdit
        self.leNormStd2_2: QtWidgets.QLineEdit
        self.leNormStd2_3: QtWidgets.QLineEdit
        self.leNormWeight1_1: QtWidgets.QLineEdit
        self.leNormWeight1_2: QtWidgets.QLineEdit
        self.leNormWeight1_3: QtWidgets.QLineEdit
        self.leNormWeight2_1: QtWidgets.QLineEdit
        self.leNormWeight2_2: QtWidgets.QLineEdit
        self.leNormWeight2_3: QtWidgets.QLineEdit
        self.leUniformMin1: QtWidgets.QLineEdit
        self.leUniformMax1: QtWidgets.QLineEdit
        self.leUniformMin2: QtWidgets.QLineEdit
        self.leUniformMax2: QtWidgets.QLineEdit
        self.LEMeanTimeSeconds1: QtWidgets.QLineEdit
        self.LEMeanTimeSeconds2: QtWidgets.QLineEdit
        self.sbUniformP1:QtWidgets.QSpinBox
        self.sbUniformP2:QtWidgets.QSpinBox
        self.DistributionWidget: QtWidgets.QLayout

        #Traffic
        self.cbTrafficSelectSeg: QtWidgets.QComboBox
        self.cbSelectType: QtWidgets.QComboBox
        self.cbTrafficDirectionSelect: QtWidgets.QComboBox
        self.twTrafficData: QtWidgets.QTableWidget
        self.dsbGlobalTrafficScaling: QtWidgets.QDoubleSpinBox
        self.pbResetTrafficScaling: QtWidgets.QPushButton
        self.gbScalingControls: QtWidgets.QGroupBox
        self.wScalingContent: QtWidgets.QWidget
        self.vlFollowGlobalCheckboxes: QtWidgets.QVBoxLayout


        # Depths
        self.pbAddSimpleDepth: QtWidgets.QPushButton
        self.pbLoadDepth: QtWidgets.QPushButton
        self.pbRemoveDepth: QtWidgets.QPushButton
        self.twDepthList: QtWidgets.QTableWidget
        self.pbGetGebcoDephts: QtWidgets.QPushButton
        self.PBUpdateDepthIntervals: QtWidgets.QPushButton
        self.LEGebcoExtension : QtWidgets.QLineEdit
        self.LEOpenTopoAPIKey: QtWidgets.QLineEdit
        self.LEMaxDepth: QtWidgets.QLineEdit
        self.SBDepthInterval:QtWidgets.QSpinBox
        self.TWDepthIntervals: QtWidgets.QTableWidget
        
        # Objects
        self.twObjectList: QtWidgets.QTableWidget   
        self.pbAddSimpleObject: QtWidgets.QPushButton
        self.pbLoadObject: QtWidgets.QPushButton
        self.pbRemoveObject: QtWidgets.QPushButton
        
        # Run analysis
        self.LEModelName: QtWidgets.QLineEdit
        self.pbRunModel: QtWidgets.QPushButton
        self.TWPreviousRuns: QtWidgets.QTableWidget
        self.pbViewDriftingAllision: QtWidgets.QPushButton
        self.LEPDriftAllision: QtWidgets.QLineEdit
        self.pbViewPoweredAllision: QtWidgets.QPushButton
        self.LEPPoweredAllision: QtWidgets.QLineEdit
        self.pbViewDriftingGrounding: QtWidgets.QPushButton
        self.LEPDriftingGrounding: QtWidgets.QLineEdit
        self.pbViewPoweredGrounding: QtWidgets.QPushButton
        self.LEPPoweredGrounding: QtWidgets.QLineEdit
        self.pbViewOvertakingCollision: QtWidgets.QPushButton
        self.LEPOvertakingCollision: QtWidgets.QLineEdit
        self.pbViewHeadOnCollision: QtWidgets.QPushButton
        self.LEPHeadOnCollision: QtWidgets.QLineEdit
        self.pbViewCrossingCollision: QtWidgets.QPushButton
        self.LEPCrossingCollision: QtWidgets.QLineEdit
        self.pbViewMergingCollision: QtWidgets.QPushButton
        self.LEPMergingCollision: QtWidgets.QLineEdit

        # Analyse drift tab
        self.leDepthThreshold: QtWidgets.QLineEdit
        self.leHeightThreshold: QtWidgets.QLineEdit
        self.pbRunDriftAnalysis: QtWidgets.QPushButton
        self.label_drift_status: QtWidgets.QLabel

    def _apply_visual_refresh(self):
        def qt_enum(owner, direct_name, scoped_group, scoped_name):
            value = getattr(owner, direct_name, None)
            if value is not None:
                return value
            return getattr(getattr(owner, scoped_group), scoped_name)

        layout_constraint = qt_enum(
            QtWidgets.QLayout,
            "SetDefaultConstraint",
            "SizeConstraint",
            "SetDefaultConstraint",
        )
        cursor_shape = qt_enum(Qt, "PointingHandCursor", "CursorShape", "PointingHandCursor")
        no_frame = qt_enum(QtWidgets.QFrame, "NoFrame", "Shape", "NoFrame")
        select_rows = qt_enum(
            QtWidgets.QAbstractItemView,
            "SelectRows",
            "SelectionBehavior",
            "SelectRows",
        )
        single_selection = qt_enum(
            QtWidgets.QAbstractItemView,
            "SingleSelection",
            "SelectionMode",
            "SingleSelection",
        )
        header_stretch = qt_enum(QtWidgets.QHeaderView, "Stretch", "ResizeMode", "Stretch")
        align_left = qt_enum(Qt, "AlignLeft", "AlignmentFlag", "AlignLeft")
        align_vcenter = qt_enum(Qt, "AlignVCenter", "AlignmentFlag", "AlignVCenter")

        self.horizontalLayout.setSizeConstraint(layout_constraint)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.setUsesScrollButtons(True)

        for line_edit in self.findChildren(QtWidgets.QLineEdit):
            line_edit.setMinimumHeight(32)

        for combo_box in self.findChildren(QtWidgets.QComboBox):
            combo_box.setMinimumHeight(32)

        # QDoubleSpinBox does *not* inherit QSpinBox, so iterate the
        # shared base class (QAbstractSpinBox) to cover both -- otherwise
        # double-spinboxes are squashed under the project font and clip
        # their text.
        for spin_box in self.findChildren(QtWidgets.QAbstractSpinBox):
            spin_box.setMinimumHeight(32)

        for button in self.findChildren(QtWidgets.QPushButton):
            button.setCursor(cursor_shape)
            button.setMinimumHeight(32)

        for scroll_area in (self.scrollArea, self.scrollArea_2):
            scroll_area.setFrameShape(no_frame)

        # twTrafficData uses its vertical header for ship-type labels, so
        # it must keep its vertical header visible.  Other tables use their
        # first column as the "name" column and don't need the header.
        _needs_vheader = {'twTrafficData'}
        for table in self.findChildren(QtWidgets.QTableWidget):
            table.setAlternatingRowColors(True)
            table.setShowGrid(False)
            table.setSelectionBehavior(select_rows)
            table.setSelectionMode(single_selection)
            table.setFrameShape(no_frame)
            table.setWordWrap(False)
            table.setCornerButtonEnabled(False)
            if table.objectName() not in _needs_vheader:
                table.verticalHeader().setVisible(False)
            table.verticalHeader().setDefaultSectionSize(28)
            table.horizontalHeader().setStretchLastSection(True)
            table.horizontalHeader().setHighlightSections(False)

        self.TWDepthIntervals.horizontalHeader().setSectionResizeMode(
            header_stretch
        )

        self.LEModelName.setPlaceholderText("Collision risk model")
        self.LEReportPath.setPlaceholderText("Select output folder")
        self.LEOpenTopoAPIKey.setPlaceholderText("OpenTopography API key")

        self.label_drift_status.setAlignment(align_left | align_vcenter)
        self.label_drift_status.setMinimumHeight(28)

    def closeEvent(self, event):
        self.closingPlugin.emit()
        self.plugin.onClosePlugin()
        event.accept()
