def initialize(self):
     self.model = HistorialPrograma(self.application.db)
     self.itemprog = ItemPrograma(self.application.db)
     self.fila = Fila(self.application.db)
     self.itemfila = ItemFila(self.application.db)
     self.punto = Punto(self.application.db)
class HistorialProgramaHandler(BaseHandler):

    def initialize(self):
        self.model = HistorialPrograma(self.application.db)
        self.itemprog = ItemPrograma(self.application.db)
        self.fila = Fila(self.application.db)
        self.itemfila = ItemFila(self.application.db)
        self.punto = Punto(self.application.db)

    @staticmethod
    def _nested_simple(data, name):
        print data
        if type(data[name]) is dict:
            rel_id = data[name]['id']
            data[name] = rel_id
        return data

    def _parse_prog(self, progid):
        tobin = {
            'itemprogramas': [],
            'filas': [],
            'puntos': [],
            'prog_id': int(progid['programa_id'])
        }

        # Agrega Items del programa

        itemprog = self.itemprog.get(progid)
        for p in itemprog:
            item = {
                'fila': p.fila_id,
                'repeticiones': p.repeticiones,
                'distancia': p.distancia,
                'velocidad': p.velocidad,
            }
            tobin['itemprogramas'].append(item)

        # Agrega Filas

        filasid = []
        n = 0
        for i in tobin['itemprogramas']:
            fid = i['fila']
            if fid is not None:
                fila = self.fila.get({'id': fid})
                if fila.id not in filasid:
                    tobin['itemprogramas'][n]['fila'] = len(filasid)
                    filasid.append(fila.id)
                    f = self.itemfila.get({'fila_id':fila.id})
                    items = []
                    for j in f:
                        item = {
                            'punto': j.punto_id,
                            'cilindros': [j.c9,j.c8,j.c7,j.c6,j.c5,j.c4,j.c3,j.c2,j.c1],
                        }
                        items.append(item)
                    tobin['filas'].append(items)
                else:
                    tobin['itemprogramas'][n]['fila'] = filasid.index(fila.id)
            else:
                tobin['itemprogramas'][n]['fila'] = 0
                tobin['itemprogramas'][n]['repeticiones'] = 0        
            n += 1

        # Agrega Puntos

        puntosid = []
        fn = 0
        for f in tobin['filas']:
            ifn = 0
            for itemf in f:
                pid = itemf['punto']
                if pid:
                    punto = self.punto.get({'id': pid})
                    if punto.id not in puntosid:
                        tobin['filas'][fn][ifn]['punto'] = len(puntosid)
                        puntosid.append(punto.id)

                        p = {
                            'potencia': punto.potencia,
                            'soldadura': punto.soldadura,
                            'presoldadura': punto.presoldadura,
                            'postsoldadura': punto.postsoldadura,
                        }
                        tobin['puntos'].append(p)

                    else:
                        tobin['filas'][fn][ifn]['punto'] = puntosid.index(punto.id)
                else:
                    print 'Break'
                ifn += 1
            fn += 1
        return tobin

    def post(self):
        self._json_args[u'programa_id'] = int(self._json_args['programa_id'])
        data = self._post_put_data(self._json_args)
        tobin = self._parse_prog(data)
        response = self.application.serial.GrabaProg(tobin)
        if response['state'] == 'success':
            query = self.model.save(data)
            self.write(escape.json_encode(query))
            self.set_header("Content-Type", "application/json")
        else:
            self.send_error(400)