# -*- coding: utf-8 -*-
"""
Simple example showing the creation of a Qt application with the NodeWidget as
the one and only widget in the application. This example also uses the default
Node library.
"""

# 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


class MainWindow(QtWidgets.QMainWindow):
    def closeEvent(self, *args, **kwargs):
        QtWidgets.qApp.quit()
        QtWidgets.QMainWindow.closeEvent(self, *args, **kwargs)


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

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

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

    # 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 = MainWindow()
    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()

