# -*- coding: utf-8 -*-
"""
Simple example showing the creation of a node with a table terminal.
"""

# append the path to allow usage of nodeworks outside of python's sitepackages
import sys
sys.path.append('../')

# import qt, qtpy is a PySide/PyQt4/PyQt5 interface that uses Qt5 syntax
# > pip install qtpy
from qtpy import QtWidgets

# Import nodeworks
from nodeworks import NodeWidget, Node


# Custom Table Node
class TableNode(Node):
    name = 'Table Node'

    def __init__(self):
        # define the terminal options
        self.terminalOpts = {
            'table': {'widget': 'table',
                      'in': True,
                      'out': False,
                      'showlabel': False,
                      'dtype': list,
                      'multiinput': False,
                      'columndelegate': {0: {'widget': None},
                                         1: {'widget': 'combobox',
                                             'items': [str(i) for i in range(100)],
                                             'dtype': str},
                                         2: {'widget': 'spinbox',
                                             'dtype': int,
                                             'min': -10,
                                             'max': 10,
                                             },
                                         3: {'widget': 'doublespinbox',
                                             'dtype': float,
                                             'min': -1,
                                             'max': 1,
                                             },
                                         4: {'widget': 'checkbox',
                                             'dtype': bool,
                                             }
                                         },
                      'rowdelegate': {},
                      'columns': ['col 1', 'col 2'],
                      'rows': None,
                      'value': [[1.1, 2, 3, 10.0, True],
                                [5, 6, 7, 8, False]],
                      'selectionBehavior': 'row',
                      'selectionMode': 'multi',
                      }
                }
        # Initialize the Node
        Node.__init__(self)

        self.terminals['table'].widget.setMinimumSize(500, 300)
        self.terminals['table'].valueChanged.connect(self.printValue)

        # resize the table to the current values
        self.terminals['table'].widget.fitToContents()

        # set a specific width of a column note: the column has to exist first
        self.terminals['table'].widget.setColumnWidth(1, 200)

        # connect the selection event to call a method
        self.terminals['table'].widget.newSelection.connect(self.newSelection)

    def printValue(self, value):
        print(value)

    def newSelection(self, from_, to):
        print('selection from:', from_, 'to', to)

    def process(self):
        print(self.terminals['table'].value)
        print(self.table.widget.currentRow())


# Custom Dictionary Node
class DictNode(Node):
    name = 'Dict Node'

    def __init__(self):
        # define the options
        self.terminalOpts = {
            'table': {'widget': 'table',
                      'in': False,
                      'out': True,
                      'showlabel': False,
                      'dtype': dict,
                      'multiinput': False,
                      'columndelegate': {0: {'widget': None},
                                         1: {'widget': 'combobox',
                                             'items': ['one', 'two', 'three',
                                                       'four', 'five', 'six'],
                                             'dtype': str},
                                         2: {'widget': 'spinbox',
                                             'dtype': int,
                                             'min': -10,
                                             'max': 10,
                                             },
                                         3: {'widget': 'doublespinbox',
                                             'dtype': float,
                                             'min': -1,
                                             'max': 1,
                                             },
                                         4: {'widget': 'checkbox',
                                             'dtype': bool,
                                             }
                                         },
                      'rowdelegate': {},
                      'columns': ['col 1', 'col 2'],
                      'rows': [],
                      'value': {10: {'col 1': 2, 'col 2': 3},
                                15: {'col 1': 4, 'col 2': 5},
                                }
                      },
            }
        # Initialize the Node
        Node.__init__(self)

        self.terminals['table'].widget.setMinimumSize(500, 300)

        self.terminals['table'].widget.fitToContents()

    def process(self):
        print(self.terminals['table'].value)


def main():
    # Create a Qt App
    app = QtWidgets.QApplication(sys.argv)

    # initialize the node widget
    nodechart = NodeWidget(showtoolbar=True)

    # Build default node library
    nodechart.nodeLibrary.buildDefaultLibrary()

    # Add the dynamic node
    nodechart.nodeLibrary.addNode(TableNode, [])
    nodechart.nodeLibrary.addNode(DictNode, [])

    # Create a menu bar
    menu = QtWidgets.QMenuBar()
    fileMenu = menu.addMenu('&File')

    # Open Action
    openAction = QtWidgets.QAction('&Open', menu)
    openAction.setShortcut('Ctrl+O')
    openAction.setStatusTip('Open a Node Chart')
    openAction.triggered.connect(nodechart.open)
    fileMenu.addAction(openAction)

    # Save Action
    saveAction = QtWidgets.QAction('&Save', menu)
    saveAction.setShortcut('Ctrl+S')
    saveAction.setStatusTip('Save a Node Chart')
    saveAction.triggered.connect(nodechart.save)
    fileMenu.addAction(saveAction)

    # Clear Action
    clearAction = QtWidgets.QAction('&Clear', menu)
    clearAction.setShortcut('Ctrl+Q')
    clearAction.setStatusTip('Clear a Node Chart')
    clearAction.triggered.connect(nodechart.deleteAllNodes)
    fileMenu.addAction(clearAction)

    # Reload Action
    reloadAction = QtWidgets.QAction('&Reload Library', menu)
    reloadAction.setShortcut('Ctrl+R')
    reloadAction.setStatusTip('Reload the Node Library')
    reloadAction.triggered.connect(nodechart.reloadLibrary)
    fileMenu.addAction(reloadAction)

    fileMenu.addSeparator()

    # Exit Action
    exitAction = QtWidgets.QAction('&Exit', menu)
    exitAction.setShortcut('Ctrl+Q')
    exitAction.setStatusTip('Exit application')
    exitAction.triggered.connect(QtWidgets.qApp.quit)
    fileMenu.addAction(exitAction)

    # create the main window
    mainwindow = QtWidgets.QMainWindow()
    mainwindow.setCentralWidget(nodechart)
    mainwindow.setMenuBar(menu)
    mainwindow.setGeometry(200, 200, 800, 500)
    mainwindow.setWindowTitle('Nodeworks')
    mainwindow.show()

    # Start Qt Event Loop
    app.exec_()
    app.deleteLater()
    sys.exit()

if __name__ == '__main__':
    main()
