from Qt import QtWidgets, QtCore, QtGui
import os
import subprocess
from wizart.desktop.projects_registry import ProjectsAggregator
from wizart.desktop.app_launch import RezApplication
import main_window
import utils


class TreeView(QtWidgets.QTreeView):
    def __init__(self, parent=None):
        super(TreeView, self).__init__(parent)
        self.setModel(QtWidgets.QFileSystemModel())
        self.model().setReadOnly(False)
        self.setDragEnabled(True)
        self.viewport().setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.openMenu)

    def openMenu(self, position):
        if self.selectedIndexes():
            menu = QtWidgets.QMenu()
            if not self.model().isDir(self.currentIndex()):
                file_path = self.currentPath()
                extension = file_path.rpartition('.')[2]
                apps = self.get_apps_to_open(extension)
                if len(apps) >= 1:
                    for app in apps:
                        def func(app=app, file_path=file_path): return app.launch([file_path])
                        menu.addAction(QtGui.QIcon(app.icon), 'Open with {}'.format(app.label), func)
            menu.addAction('Copy', self.copy)
            menu.addAction('Paste', self.paste)
            menu.addAction('Rename', self.edit_item)
            menu.addAction('Remove', self.remove_item)
            menu.exec_(self.viewport().mapToGlobal(position))

    def paste(self):
        index = self.currentIndex()
        if not self.model().isDir(index):
            index = self.model().parent(index)
        data = QtWidgets.QApplication.instance().clipboard().mimeData()
        self.model().dropMimeData(data, QtCore.Qt.CopyAction, 0, 0, index)

    def edit_item(self):
        self.edit(self.currentIndex())

    def remove_item(self):
        self.model().remove(self.currentIndex())

    def copy(self):
        path = self.currentPath()
        clipboard = QtWidgets.QApplication.instance().clipboard()
        data = QtCore.QMimeData()
        url = QtCore.QUrl.fromLocalFile(path)
        data.setUrls([url])
        clipboard.setMimeData(data)

    def mouseDoubleClickEvent(self, event):
        index = self.indexAt(event.pos())
        if self.model().isDir(index):
            self.setExpanded(index, not self.isExpanded(index))
        else:
            point = event.pos()
            self.open_file(point)

    def get_apps_to_open(self, extension):
        project = main_window.DesktopWindow.instance().get_project()
        if not project:
            return
        rez_apps = [app for app in ProjectsAggregator.get_apps_for_project(
            project.name) if isinstance(app, RezApplication)]
        finded_apps = filter(lambda app: extension in app.extension, rez_apps)
        return finded_apps

    def currentPath(self):
        index = self.currentIndex()
        path = self.model().filePath(index)
        return path

    def open_file(self, point):
        file_path = self.currentPath()
        extension = file_path.rpartition('.')[2]
        apps = self.get_apps_to_open(extension)
        if len(apps) == 0:
            return
        elif len(apps) == 1:
            apps[0].launch([file_path])
        elif len(apps) >= 2:
            menu = QtWidgets.QMenu()
            for app in apps:
                def func(app=app, file_path=file_path): return app.launch(
                    [file_path])
                menu.addAction(QtGui.QIcon(app.icon), app.label, func)
            menu.exec_(self.viewport().mapToGlobal(point))


class WorkspaceTab(QtWidgets.QWidget):
    def __init__(self, app, parent=None):
        super(WorkspaceTab, self).__init__(parent)
        self.app = app
        self.setObjectName("workspace")
        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.workspace_name = QtWidgets.QLabel("<b>Workspace</b>")
        top_layout.addWidget(self.back_btn)
        top_layout.addStretch()
        top_layout.addWidget(self.workspace_name)
        top_layout.addStretch()

        btn_layout = QtWidgets.QHBoxLayout()
        self.layout().addLayout(btn_layout)
        btn_layout.addStretch()
        self.open_folder_btn = QtWidgets.QPushButton("Open Folder in Explorer")
        self.open_folder_btn.released.connect(self.open_work_folder_explorer)
        btn_layout.addWidget(self.open_folder_btn)

        self.workspace_view = TreeView(self)
        self.workspace_view.setAcceptDrops(True)
        self.workspace_view.setDropIndicatorShown(True)
        self.workspace_view.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection )
        self.layout().addWidget(self.workspace_view)


    def set_workspace(self, title, path):
        self.workspace_name.setText('<b>{0} ({1})<b>'.format(title, path))
        self.workspace_view.model().setRootPath(path)
        self.workspace_view.setRootIndex(self.workspace_view.model().index(path))

    def open_work_folder_explorer(self):
        index = self.workspace_view.rootIndex()
        if index.isValid():
            path = index.data(QtWidgets.QFileSystemModel.FilePathRole)
            path = os.path.normpath(path)
            subprocess.call('explorer "%s"' % path, shell=True)
