import collections

from gamera.plugins import _string_io
from gamera.toolkits.musicstaves import *

from OMRnotes.scripts.classification.find.heads import findheads
from OMRnotes.scripts.classification.lines import Lines
from OMRnotes.scripts.classification.segmenter import Segmenter
from OMRnotes.scripts.post.parser import Parser
from OMRnotes.scripts.pre.morph import Morph
from OMRnotes.scripts.pre.staves import msrlinetracking
from OMRnotes.scripts.utils.view import ImageView

init_gamera()

_modes = {3       : 'RGB',
          1       : 'GRAY'}

class Chain:
    '''Retezec skriptu
    '''
    def __init__(self):
        self.images = collections.defaultdict(dict)
        self.mor = Morph()
        self.seg = Segmenter()

    def execute(self, idin, idout, task):
        class Chain:
            '''Vykonavaci algoritmus retezce
            
            Pre: Preprocessing
            
            Staff: Odstaneni notovych linek
            
            Horlines: Detekce linek
            
            Head: Detekce hlavicek not
            
            v soucane dobe jsou mnohe funkce vyrazeny z provozu
            generace xml souboru je primo v detekci hlavicek not
            '''
        if task == 'pre':
            try:
                im = self.images[str(idin)]['orig']
            except KeyError:
                return False
            imgout = im.djvu_threshold(0.2, 512, 64, 2)
            self.images[str(idout)]['pre'] = imgout
        elif task == 'staff':
            try:
                im = self.images[str(idin)]['pre']
            except KeyError:
                return False
            sf = msrlinetracking(im)
            lines = Lines(sf.stafffinder.linelist, sf.staffline_height, sf.staffspace_height)
            imgout = sf.image.image_copy()
            staffcc = self.seg.getcc(imgout)
            self.images[str(idout)]['staff'] = imgout
            self.images[str(idout)]['staffdata'] = sf
            self.images[str(idout)]['stafflines'] = lines
            self.images[str(idout)]['staffcc'] = staffcc
        elif task == 'horlines':
            try:
                im = self.images[str(idin)]['staff']
                sf = self.images[str(idout)]['staffdata']
            except KeyError:
                return False
            imgfh2 = self.mor.filterhor2(im)
            filterline2 = self.mor.filterline2(im, sf)
            ccc = self.seg.findlines(filterline2, im)
            #self.images[str(idout)]['horlines'] = ccc
            self.images[str(idout)]['imgfl2'] = filterline2
        elif task == 'head':
            try:
                im = self.images[str(idin)]['staff']
                lines = self.images[str(idin)]['stafflines']
                #ccc = self.images[str(idin)]['horlines']
            except KeyError:
                return False
            imgfhv1 = self.mor.filterhorver1(im)
            drawtemp = im.to_rgb()
            heads = findheads(im, imgfhv1, lines, drawtemp)
            par = Parser(heads)
            #imgdelheadslines = self.seg.deleteheadslines(heads, imgfh2)
            #imgdelheads = self.seg.deleteheads(heads, im)
            #imgdelnotescc = self.seg.getcc(imgdelheadslines)

            #self.seg.getdots(heads, staffcc, imgdelnotescc, sf)
            #self.seg.getflags(heads, staffcc, imgdelnotescc, sf)
            #beams = self.seg.findbeams(heads, imgdelheads)
            #imgdelfullnotes = self.seg.deletefullnotes(heads, beams, imgfh2)
            #imgdelfullnoteslines = self.seg.deletesegments(ccc, imgdelfullnotes)
            #halfheads = self.seg.findhalfheads(ccc, imgdelfullnoteslines, sf)
            #imgdelallnotes = self.seg.deletefullnotes(heads, beams, im)
            #imgdelallnotes = self.seg.deletehalfnotes(halfheads, imgdelallnotes)
            #imgdelallnotesdil = self.mor.morphology(imgdelallnotes, 'dilate', 4, 1)
            #imgdelallnotesdilcc = self.seg.getcc(imgdelallnotesdil)
            #imgdelallnotescc = self.seg.getcc(imgdelallnotes)
            #otherseg = self.seg.subcc(imgdelallnotescc, imgdelallnotesdilcc, 1)

            self.images[str(idout)]['drawtemp'] = drawtemp
            self.images[str(idout)]['imgfhv1'] = imgfhv1
            self.images[str(idout)]['head'] = heads
            #self.images[str(idout)]['halfhead'] = halfheads
            #self.images[str(idout)]['beam'] = beams
            #self.images[str(idout)]['imgdel'] = imgdel
            #self.images[str(idout)]['imgdelcc'] = imgdelnotescc
            #self.images[str(idout)]['imgdelheadslines'] = imgdelheadslines
            #self.images[str(idout)]['imgdelheads'] = imgdelheads
            #self.images[str(idout)]['imgdellines'] = imgdellines
            #self.images[str(idout)]['imgdelfullnotes'] = imgdelfullnotes
            #self.images[str(idout)]['imgdelallnotes'] = imgdelallnotes
            #self.images[str(idout)]['imgdelallnotesdil'] = imgdelallnotesdil
            #self.images[str(idout)]['otherseg'] = otherseg
        return True


    def imgGet(self, id, task):
        '''Funkce pro generovani obrazoveho vystupu pro neobrazove polozky v databazi
        
        Horlines: nakresli linky
        
        Head: nakresli hlavicky
        
        otherseg: vyznaci ostatni segmenty
        
        '''
        if task == 'horlines':
            try:
                data = self.images[str(id)]['horlines']
                img = self.images[str(id)]['staff']
                view = self.images[str(id)]['viewer']
            except KeyError:
                return None
            im = view.drawlines(data, img)
        elif task == 'head':
            try:
                heads = self.images[str(id)]['head']
                img = self.images[str(id)]['staff']
                #beams = self.images[str(id)]['beam']
                view = self.images[str(id)]['viewer']
            except KeyError:
                return None
            im = view.drawheads(heads, img)
            #im = view.drawBeams(beams, im)
        elif task == 'halfhead':
            try:
                halfheads = self.images[str(id)]['halfhead']
                img = self.images[str(id)]['staff']
                view = self.images[str(id)]['viewer']
            except KeyError:
                return None
            im = view.drawhalfheads(halfheads, img)
        elif task == 'otherseg':
            try:
                otherseg = self.images[str(id)]['otherseg']
                img = self.images[str(id)]['staff']
                view = self.images[str(id)]['viewer']
            except KeyError:
                return None
            im = view.drawothers(otherseg, img)
        else:
            try:
                data = self.images[str(id)][task]
            except KeyError:
                return None
            im = data
        return self.toRaw(im)


    def openfile(self, ids, path):
        '''Otevre soubor knihovnou Gamera
        Ulozi zakladni polozky do knihovny
        '''
        img = load_image(path)
        imgrgb = img.to_rgb()
        self.images[str(ids)]['orig']=imgrgb
        self.images[str(ids)]['viewer'] = ImageView()
        return self.toRaw(imgrgb)

    def toRaw(self, img):
        '''Prevede soubor na RAW
        pro konverzi do jinych knihoven
        '''
        pixel_type = img.data.pixel_type
        if _modes.has_key(pixel_type):
            mode = _modes[pixel_type]
            size = (img.ncols, img.nrows)
            rawec = _string_io._to_raw_string(img)
        else:
            newimg = img.to_rgb()
            mode = _modes[3]
            size = (newimg.ncols, newimg.nrows)
            rawec = _string_io._to_raw_string(newimg)

        return [rawec, img.ncols, img.nrows, mode]




