# -*- coding: utf-8 -*-
"""
Simple example showing how threads work with long running nodes.
"""

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

# import other modules
import time
import random
from collections import OrderedDict

# 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


class DelayNode(Node):
    name = 'delay node'

    def __init__(self):
        self.terminalOpts = OrderedDict([
            ('dep', {'widget': 'doublespinbox',
                     'in': True,
                     'out': False,
                     'showlabel': True,
                     'dtype': float,
                     'value': 5,
                     }),
            ('sleep', {'widget': 'display',
                       'in': False,
                       'out': True,
                       'showlabel': True,
                       'dtype': float,
                       }),
            ])
        Node.__init__(self)

    def process(self):

        random_sleep = random.random()*self.terminals['dep'].value

        time.sleep(random_sleep)
        self.terminals['sleep'].setValue('{0:.1f}'.format(random_sleep))


class LongProcessNode(Node):
    name = 'long process node'

    def __init__(self):
        self.terminalOpts = OrderedDict([
            ('iterations', {'widget': 'lineedit',
                            'in': True,
                            'out': False,
                            'showlabel': True,
                            'dtype': int,
                            'value': 10000000,
                            'multiinput': True,
                            }),
            ('out', {'widget': 'display',
                     'in': False,
                     'out': True,
                     'showlabel': True,
                     'dtype': int,
                     }),
            ])
        Node.__init__(self)

    def process(self):

        itr = sum(self.terminals['iterations'].value)

        l = ''
        for i in range(itr):
            l += 'f'
            time.sleep(0.002)

        self.terminals['out'].value = itr


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

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

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

    # Add the dynamic node
    for node in [DelayNode, LongProcessNode]:
        nodechart.nodeLibrary.addNode(node, [])

    # create the main window
    mainwindow = QtWidgets.QMainWindow()
    mainwindow.setCentralWidget(nodechart)
    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()
