import tempfile
import uuid
import os, sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from wand.image import Color as Wandcolor
from wand.image import Image as Wandimage

from OMRnotes.gui import *
from OMRnotes.gui.mainwindow import Ui_MainWindow
from OMRnotes.scripts.chain import *

filter = "Image files (*.jpg *.gif *.png)"

class MyFirstGuiProgram(QMainWindow, Ui_MainWindow):
    """Hlavni obrazovka programu
    """
    def treeView_doubleClicked(self, index):
        item = self.treeView.selectedIndexes()[0]
        self.graph.setPhoto(item.model().itemFromIndex(index).getImage())


    def __init__(self):
        super(QMainWindow, self).__init__()
        self.setupUi(self)
        self.actionOpen.triggered.connect(self.openImage)
        self.actionOpen_images.triggered.connect(self.openImages)
        self.actionOpen_PDF.triggered.connect(self.openPDF)
        self.actionRun.triggered.connect(self.convert)
        self.actionRun_all.triggered.connect(self.convertall)
        self.graph = PhotoViewer(self.centralwidget)
        self.verticalLayout_2.insertWidget(0,self.graph)
        self.progressBar = QProgressBar()
        self.statusbar.addPermanentWidget(self.progressBar)
        self.progressBar.setGeometry(30, 40, 200, 16)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(0)
        self.model = QStandardItemModel()
        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
        self.treeView.doubleClicked.connect(self.treeView_doubleClicked)
        self.treeView.setModel(self.model)
        self.dirpath = tempfile.mkdtemp()
        self.imgpath = os.path.join(os.getcwd(), "../tests/notes")
        self.item = {}
        self.rungam = Chain()

        #self.directImage('../tests/notes/pec.png')
        #self.directImage('../tests/notes/notateme52.png')
        #self.directImage('../tests/learning/test/page-4.png')
        #self.directImage('../tests/notes/multi.png')
        #self.directImage('../tests/notes/polonez3.gif')

        self.convertall()

    def convertall(self):
        """Provede vsechny retezce
        """
        for key, value in self.item.items():
            value.runAll()

    def __del__(self):
        # Obnovi sys.stdout
        sys.stdout = sys.__stdout__

    def convert(self):
        """Provede retezec
        """
        item = self.treeView.selectedIndexes()[0]
        crawler = item.model().itemFromIndex(item)
        crawler.run()
        self.graph.setPhoto(crawler.getImage())

    def normalOutputWritten(self, text):
        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.textEdit.setTextCursor(cursor)
        self.textEdit.ensureCursorVisible()

    def getpdf(self):
        """Otevre dialogove okno pro vyber pdf souboru
        """
        sites, ok = Pdfdialog.show()

    def openImages(self):
        """Otevre dialogove okno
        """
        names = QFileDialog.getOpenFileNames(self, "Open files", self.imgpath, filter)
        for path in names[:-1][0]:
            self.directImage(path)

    def openPDF(self):
        """Otevre dialogove okno pro soubory pdf
        """
        fname = QFileDialog.getOpenFileName(self, 'Open file', self.imgpath, '*.pdf')
        filepath = QFileInfo(fname[0])
        print "Open to convert " + filepath.absoluteFilePath()
        if filepath.exists():
            id = uuid.uuid4()
            with Wandimage(filename=fname[0], resolution=300) as img:
                pages = Pdfdialog.show(len(img.sequence))
                for i, page in enumerate(img.sequence):
                    if (i+1) in pages[0]:
                        with Wandimage(width=img.width, height=img.height, background=Wandcolor("white")) as page_image:
                            page_image.composite(Wandimage(page), 0, 0)
                            page_image.save(filename=self.dirpath + '/' + str(id) + '-page-' + str(i+1) + '.png')
            for i in pages[0]:
                path = self.dirpath + '/' + str(id) + '-page-' + str(i) + '.png'
                self.directImage(path)

    def loadImage(self, id, file):
        """Nacte obrezek do retezce
        """
        filepath = QFileInfo(file)
        if filepath.exists():
            data = self.rungam.openfile(id, filepath.absoluteFilePath())
            self.item[id] = ImageItems(id, self.model, data, filepath.baseName(), self.rungam)
            self.graph.setPhoto(self.item[id].itemx.getImage())

    def openImage(self):
        """Overeni jednoho obrazku
        """
        path = self.openDialog()
        self.directImage(path)

    def openDialog(self):
        """Otevre dialogove okno pro jeden obrazek
        """
        fname = QFileDialog.getOpenFileName(self, 'Open file', self.imgpath, filter)
        return fname[0]


    def normalize(self, imgid, file, dir):
        """Prevede obrazek na typ png
        """
        with Wandimage(filename=file) as img:
            filename = self.dirpath + '/' + str(imgid) + '.png'
            img.save(filename=filename)
            return filename

    def directImage(self, path):
        """Vygeneruje obrazku indentifikacni cislo
        """
        filepath = QFileInfo(path)
        print "Open " + filepath.absoluteFilePath()
        if filepath.exists():
            imgid = uuid.uuid4()
            file = self.normalize(imgid, filepath.absoluteFilePath(), self.dirpath)
            self.loadImage(imgid, file)


if __name__ == '__main__':
    """Hlavni smycka programu
    """
    app = QApplication(sys.argv)
    prog = MyFirstGuiProgram()
    prog.show()
    sys.exit(app.exec_())