from Qt import QtWidgets, QtCore, QtGui

import os, pprint, json
import workspace_utils


class AddWorkspaceDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle("Add workspace")
        self.setLayout(QtWidgets.QVBoxLayout())

        layout_title = QtWidgets.QHBoxLayout()
        layout_title.addWidget(QtWidgets.QLabel("Title:"))
        self.title_le = QtWidgets.QLineEdit(self)
        layout_title.addWidget(self.title_le)
        self.layout().addLayout(layout_title)

        layout_path = QtWidgets.QHBoxLayout()
        layout_path.addWidget(QtWidgets.QLabel("Path:"))
        self.path_le = QtWidgets.QLineEdit(self)
        layout_path.addWidget(self.path_le)
        self.path_select_btn = QtWidgets.QPushButton("...")
        self.path_select_btn.setMaximumWidth(25)
        self.path_select_btn.released.connect(self.select_dir)
        layout_path.addWidget(self.path_select_btn)
        self.layout().addLayout(layout_path)

        layout_btn = QtWidgets.QHBoxLayout()
        self.ok_btn = QtWidgets.QPushButton("OK")
        self.ok_btn.released.connect(self.accept)
        layout_btn.addWidget(self.ok_btn)
        self.cancel_btn = QtWidgets.QPushButton("Cancel")
        self.cancel_btn.released.connect(self.reject)
        layout_btn.addWidget(self.cancel_btn)
        self.layout().addLayout(layout_btn)

    def select_dir(self):
        dir_path = QtWidgets.QFileDialog.getExistingDirectory(self) + "/"
        dir_path = dir_path.replace("\\", "/")
        self.path_le.setText(dir_path)


class WorkspacesListTab(QtWidgets.QWidget):
    show_workspace_signal = QtCore.Signal(int)

    def __init__(self, app, db_manager, parent=None):
        super(WorkspacesListTab, self).__init__(parent)
        self.app = app
        self.setObjectName("workspaces_list")
        self.setLayout(QtWidgets.QVBoxLayout())
        self.label = QtWidgets.QLabel("<b>Workspaces List</b>")
        self.layout().addWidget(self.label)

        self.btn_layout = QtWidgets.QHBoxLayout()
        self.layout().addLayout(self.btn_layout)

        self.btn_add = QtWidgets.QPushButton("Add", self)
        self.btn_add.pressed.connect(self.add_workspace)
        self.btn_remove = QtWidgets.QPushButton("Remove", self)
        self.btn_remove.pressed.connect(self.remove_workspaces)

        self.btn_layout.addWidget(self.btn_add)
        self.btn_layout.addWidget(self.btn_remove)

        self.list_widget = QtWidgets.QListWidget(self)
        self.list_widget.itemDoubleClicked.connect(self.open_workspace)
        self.list_widget.setSelectionMode(QtWidgets.QListWidget.ExtendedSelection)
        self.layout().addWidget(self.list_widget)
        self._workspace_db = db_manager
        self.update_list()

    def update_list(self):
        self.list_widget.clear()
        workspaces = self._workspace_db.get_workspaces()
        for workspace in workspaces:
            item = QtWidgets.QListWidgetItem(
                "{0} ({1})".format(workspace.title, workspace.path)
            )
            self.list_widget.addItem(item)
            item.workspace = workspace

    def open_workspace(self, item):
        self.show_workspace_signal.emit(item.workspace.id)

    def add_workspace(self):
        diag = AddWorkspaceDialog()
        result = diag.exec_()
        if result:
            title = diag.title_le.text()
            path = diag.path_le.text()
            self.create_workspace(path, title)
        self.update_list()

    def create_workspace(self, path, title=None):
        if not os.path.exists(path):
            os.makedirs(path)
        json_path = os.path.join(path, "workspace.json")
        if not os.path.exists(json_path):
            with open(os.path.join(path, "workspace.json"), "w") as f:
                f.write(json.dumps({"repath": {}, "pin": {}}, indent=4, sort_keys=True))
        self._workspace_db.add_workspace(path, title)
        self.update_list()

    def remove_workspaces(self):
        selected = self.list_widget.selectedItems()
        for item in selected:
            self._workspace_db.delete_workspace(item.workspace.id)
        self.update_list()
