from Qt import QtWidgets, QtCore, QtGui
from wizart.desktop.projects_registry import ProjectsAggregator
from app_launch import RezApplication

class AppsTab(QtWidgets.QWidget):
    def __init__(self, app, parent = None):
        super(AppsTab, self).__init__(parent)
        self.app = app
        self.setObjectName("apps")
        self.setLayout(QtWidgets.QVBoxLayout())
        top_layout = QtWidgets.QHBoxLayout()
        self.layout().addLayout(top_layout)
        font = QtGui.QFont("Font Awesome 5 Free Solid", 16)
        chevron_left_code = u"\uf053"
        self.back_btn = QtWidgets.QPushButton(chevron_left_code)
        self.back_btn.setFont(font)
        self.back_btn.setMaximumWidth(25)
        self.back_btn.setFlat(True)
        self.project_icon = QtWidgets.QLabel()
        self.project_icon.setMaximumSize(QtCore.QSize(42,42))
        self.project_icon.setScaledContents(True)
        self.project_name = QtWidgets.QLabel()
        top_layout.addWidget(self.back_btn)
        top_layout.addStretch()
        top_layout.addWidget(self.project_icon)
        top_layout.addWidget(self.project_name)
        top_layout.addStretch()

        self.list_widget = QtWidgets.QListWidget()
        self.list_widget.setViewMode( QtWidgets.QListView.IconMode)
        self.list_widget.setMovement(QtWidgets.QListView.Static)
        self.list_widget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        self.list_widget.setResizeMode(QtWidgets.QListView.Adjust)
        self.list_widget.setIconSize(QtCore.QSize(100,100))
        self.layout().addWidget(self.list_widget)
        self.list_widget.mousePressEvent = self.list_widget_mouse_press_event

        def _app_launch(item):
            if hasattr(item, "_obj"):
                item._obj.launch()

        self.list_widget.itemActivated.connect(_app_launch)

        def _contextMenuEvent( event):
            item = self.list_widget.itemAt(event.x(), event.y())
            if item:
                menu = QtWidgets.QMenu(self.list_widget)
                if isinstance(item._obj, RezApplication):
                    if item._obj.external is True:
                        menu.addAction("Scan for software", item._obj.scan_for_software)
                        menu.addAction("Set software executable path", item._obj.set_executable_location_diag)
                menu.addAction("Create Desktop Shortcut",item._obj.create_desktop_shortcut)
                if isinstance(item._obj, RezApplication):
                    menu.addSeparator()
                    menu.addAction("Set rez modifiers", item._obj.show_rez_modifier_dialog)
                    menu.addAction("Start Shell in App Environment", lambda: item._obj.launch(debug_env = True) )
                menu.exec_(event.globalPos())

        self.list_widget.contextMenuEvent = _contextMenuEvent
        self.apps = []
        self.update_apps()

    def list_widget_mouse_press_event(self, event):
        if event.button() == QtCore.Qt.LeftButton and event.modifiers() == QtCore.Qt.ShiftModifier:
            item = self.list_widget.currentItem()
            if item:
                drag = QtGui.QDrag(self)
                mimeData = item._obj.create_desktop_shortcut_mimedata()
                drag.setMimeData(mimeData)
                drag.setPixmap(item.icon().pixmap(64,64) )
                drag.setHotSpot( QtCore.QPoint( drag.pixmap().width()/2, drag.pixmap().height()/2)    )
                drag.exec_(QtCore.Qt.MoveAction)
                return
        return QtWidgets.QListWidget.mousePressEvent(self.list_widget, event)

    def update_apps(self):
        from wizart.desktop import main_window
        project = main_window.DesktopWindow.instance().get_project()
        if not project:
            return

        self.apps = ProjectsAggregator.get_apps_for_project(project.name)
        self.list_widget.clear()
        for app in self.apps:
            if app.is_allowed_for_user_hook() is False:
                continue
            item = QtWidgets.QListWidgetItem(self.list_widget)
            item.setIcon(QtGui.QIcon(app.icon))
            item.setText(app.label)
            item._obj = app
            if isinstance(item._obj, RezApplication):
                if app.external is True:
                    def _update_state(app, item):
                        if app.get_executable_location() is None:
                            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEnabled)
                        else:
                            item.setFlags(item.flags() | QtCore.Qt.ItemIsEnabled)
                    _update_state(app, item)
                    app.location_changed.connect( lambda app=app, item = item: _update_state(app, item) )

                def _change_background_color(app, item):
                    if app.rez_modifier_is_used and app.rez_modifiers:
                        item.setBackground(QtGui.QColor(0, 177, 106, 100))
                    else:
                        item.setBackground(QtCore.Qt.transparent)
                _change_background_color(app, item)
                app.rez_modifier_changed.connect(lambda app=app, 
                                                 item = item: _change_background_color(app, item))
    
    def set_project(self, proj):
        if proj:
            self.project_icon.setPixmap(QtGui.QPixmap(proj.icon))
            self.project_name.setText("<b>%s</b>" % proj.label)
        else:
            self.project_icon.setPixmap(QtGui.QPixmap())
            self.project_name.setText("")
