from pyqt_compat import QtWidgets


import pytuflow as pt
from pytuflow import tuflow_binaries

#from pt import tuflow_binaries

from pyqt_compat.compatibility_routines import (QT_ABSTRACT_ITEM_VIEW_NO_EDIT_TRIGGERS, QT_ABSTRACT_ITEM_VIEW_SINGLE_SELECTION,
                                      QT_ABSTRACT_ITEM_VIEW_SELECT_ROWS, QT_RICH_TEXT)


class AvailableVersionsMixin:

    def _init_available_versions(self, layout: QtWidgets.QBoxLayout) -> QtWidgets.QWidget:
        self.available_versions_widget = QtWidgets.QWidget()
        self.available_versions_layout = QtWidgets.QVBoxLayout()
        self.available_versions_widget.setLayout(self.available_versions_layout)

        self.label = QtWidgets.QLabel(
            '<b>Available TUFLOW versions</b>.<p><p>This is a read-only list of available TUFLOW version. Versions '
            'can be added in the "Locations" tab. This list will refresh automatically when changes are made '
            'to the locations.'
        )
        self.label.setTextFormat(QT_RICH_TEXT)
        self.label.setWordWrap(True)
        self.available_versions_layout.addWidget(self.label)

        self.version_table = QtWidgets.QTableWidget()
        self.version_table.setColumnCount(2)
        self.version_table.setHorizontalHeaderLabels(['Version', 'Source'])
        self.version_table.horizontalHeader().setStretchLastSection(True)
        self.version_table.setEditTriggers(QT_ABSTRACT_ITEM_VIEW_NO_EDIT_TRIGGERS)
        self.version_table.setSelectionBehavior(QT_ABSTRACT_ITEM_VIEW_SELECT_ROWS)
        self.version_table.setSelectionMode(QT_ABSTRACT_ITEM_VIEW_SINGLE_SELECTION)
        self.available_versions_layout.addWidget(self.version_table)

        # add versions
        self.refresh_available_versions()

        layout.addWidget(self.available_versions_widget)

        self.available_versions_widget.hide()
        return self.available_versions_widget

    def refresh_available_versions(self):
        tuflow_binaries.load_versions()
        self.version_table.setRowCount(tuflow_binaries.count())
        items = sorted(tuflow_binaries.items(), key=lambda x: x[0], reverse=True)
        for i, (version, bin_loc) in enumerate(items):
            version_item = QtWidgets.QTableWidgetItem(version)
            version_item.setToolTip(version)
            loc_item = QtWidgets.QTableWidgetItem(bin_loc)
            loc_item.setToolTip(bin_loc)
            self.version_table.setItem(i, 0, version_item)
            self.version_table.setItem(i, 1, loc_item)
