from PyQt5.QtGui import *

__all__ = ['StandardItem']

class StandardItem(QStandardItem):
    '''Propojeni QT seznamu s retezci
    '''
    pixmap = None

    def __init__(self, id, type, executor, data, *__args):
        QStandardItem.__init__(self, *__args)
        self.type = type
        self.executor = executor
        self.id = id

        if data:
            self.pixmap = self.toImage(data)

    def execute(self, idin):
        '''Vykona danou operaci v retezci
        '''
        print 'execute ' + str(self.type) + ' on ' + str(idin) + ' to ' + str(self.id)
        if idin == None:
            pass
        else:
            pass
        if(self.executor.execute(idin, self.id, self.type)):
            data = self.executor.imgGet(self.id, self.type)
            if data:
                pixmap = self.toImage(data)
                self.setImage(pixmap)
            else:
                print 'error ' + str(self.type) + ' on ' + str(idin) + ' to ' + str(self.id)


    def getID(self):
        '''Ziska prirazene id
        '''
        return self.id

    def getType(self):
        '''Ziska prirazene id
        '''
        return self.id


    def toImage(self, data):
        '''Prevede string obrazku do formatu QT
        '''
        if (data[3] == 'RGB'):
            bytesPerLine = (data[1]) * 3
            format = QImage.Format_RGB888
        elif (data[3] == 'GRAY'):
            bytesPerLine = data[1]
            format=QImage.Format_Grayscale8
        return QPixmap.fromImage(QImage(data[0], data[1], data[2], bytesPerLine, format))

    def getImage(self):
        '''Ziska obrazek
        '''
        return self.pixmap

    def setImage(self, pixmap):
        '''Ziska obrazek
        '''
        self.pixmap = pixmap

    def run(self):
        '''Ziska index prvku v seznamu pro vykonavaci funkci
        '''
        index = self.index()
        row = index.row()
        if(row==0):
            par = index.parent()
            if par.isValid():
                idin = self.model().itemFromIndex(par).getID()
            else:
                idin = None
        else:
            sib = index.sibling(row-1,0)
            if(sib.isValid()):
                idin = self.model().itemFromIndex(sib).getID()
            else:
                pass #exception

        self.execute(idin)

        #idchild = []
        #type = []
        #me = self.model().itemFromIndex(index)
        #for i in range(me.rowCount):
        #    idchild.append(me.child(i,0).getID())
        #    type.append(me.child(i, 0).getType())
        #self.run(idin, [idchild, type])