# -*- coding: latin-1 -*-

#==========================================================================================================================================
import copy

from PySide import QtGui

from Code.Traducir import tr
import Code.Tareas as Tareas

import QTUtil2
import Colocacion
import Iconos
import Controles
import Columnas
import Grid

def tipoVariables() :
    return (
                ( tr("TUT_VARIABLES_TIPO_TEXTO"), Tareas.VTEXTO ),
                ( tr("TUT_VARIABLES_TIPO_ENTERO"), Tareas.VENTERO ),
                ( tr("TUT_VARIABLES_TIPO_DECIMAL"), Tareas.VDECIMAL ),
            )

#==========================================================================================================================================
class WET_Variable( QtGui.QDialog ):

    def __init__( self, owner, numVariable, liVariables, tipo=None ) :

        super(WET_Variable, self).__init__(owner)

        if numVariable == -1 :
            if tipo == Tareas.VTEXTO :
                inicial = ""
            elif tipo == Tareas.VENTERO :
                inicial = 0
            elif tipo == Tareas.VDECIMAL :
                inicial = 0.0
            self.regVariable = Tareas.Variable( "", tipo, inicial )
        else :
            self.regVariable = copy.deepcopy(liVariables[numVariable])
            tipo = self.regVariable.tipo
        self.liVariables = liVariables
        self.numVariable = numVariable

        liAcciones = [  ( tr( "ME_GRABAR" ), Iconos.TB_Aceptar(), "grabar" ), None,
                        ( tr( "CANCELAR" ), Iconos.TB_Cancelar(), "reject" ), None,
                    ]
        tb = Controles.TB( self, liAcciones )

        # nombre
        lbNombre = Controles.LB( tr( "TIT_NOMBRE" ) + " :" )
        self.edNombre = Controles.ED( self, self.regVariable.nombre ).anchoFijo( 180 )

        # Según el tipo
        self.ed = Controles.ED(self)
        inicial = self.regVariable.inicial
        if tipo == Tareas.VTEXTO :
            txt = tr( "TUT_VARIABLES_TIPO_TEXTO" )
            self.ed.anchoFijo( 280 ).ponTexto(inicial)
        elif tipo == Tareas.VENTERO :
            txt = tr( "TUT_VARIABLES_TIPO_ENTERO" )
            self.ed.tipoInt(inicial).anchoFijo( 60 )
        elif tipo == Tareas.VDECIMAL :
            txt = tr( "TUT_VARIABLES_TIPO_DECIMAL" )
            self.ed.tipoFloat(inicial,decimales=2).anchoFijo( 60 )
        lb = Controles.LB( txt + " :")
        self.setWindowTitle( txt )

        # Layout edicion
        ly = Colocacion.G().controld( lbNombre, 0, 0 ).control( self.edNombre, 0, 1 )
        ly.controld( lb, 1, 0 ).control( self.ed, 1, 1 )

        # Layout
        layout = Colocacion.V().control(tb).otro(ly).relleno(1)
        self.setLayout( layout )

    #--------------------------------------------------------------------------------------------------------------------------------
    def procesarTB( self ) :
        accion = self.sender().clave
        eval( "self.%s()"%accion )

    #--------------------------------------------------------------------------------------------------------------------------------
    def grabar( self ) :
        nombre = self.edNombre.texto()
        if nombre == "" :
            QTUtil2.mensError( self, tr("TUT_FM_FALTANOMBRE"))
            return

        for nf, rf in enumerate(self.liVariables) :
            if nf != self.numVariable :
                if rf.nombre.lower() == nombre :
                    QTUtil2.mensError( self, tr("TUT_FM_NOMBREREPETIDO"))
                    return

        self.regVariable.nombre = nombre
        tipo = self.regVariable.tipo
        if tipo == Tareas.VTEXTO :
            inicial = self.ed.texto()
        elif tipo == Tareas.VENTERO :
            inicial = self.ed.textoInt()
        elif tipo == Tareas.VDECIMAL :
            inicial = self.ed.textoFloat()
        self.regVariable.inicial = inicial

        self.accept()

#==========================================================================================================================================
class WET_Variables( QtGui.QWidget ):

    def __init__( self, wowner, owner ) :

        QtGui.QWidget.__init__(self,wowner)

        f = Controles.TipoLetra( puntos=12, peso = 75 )
        flb = Controles.TipoLetra( puntos=8 )

        self.tutorial = owner.tutorial
        self.liVariables = self.tutorial.liVariables
        self.dicTipos = {}
        for txt, clave in tipoVariables() :
            self.dicTipos[clave] = txt

        # Lista
        oColumnas = Columnas.ListaColumnas()
        oColumnas.nueva( "NUMERO", tr( "AB_NUM" ), 60, siCentrado=True )
        oColumnas.nueva( "NOMBRE", tr( "TIT_NOMBRE" ), 240 )
        oColumnas.nueva( "TIPO", tr( "TUT_VARIABLES_TIPO" ), 120 )
        oColumnas.nueva( "INICIAL", tr( "TUT_VARIABLES_INICIAL" ), 256 )

        self.grid = Grid.Grid( self, oColumnas, id = "V", siSelecFilas=True )

        liAcciones = [  ( tr( "NUEVO" ), Iconos.TB_Nuevo(), "mas" ), None,
                        ( tr( "BORRAR" ), Iconos.TB_Borrar(), "borrar" ), None,
                        ( tr( "MODIFICAR" ), Iconos.TB_Modificar(), "modificar" ), None,
                        ( tr( "ARRIBA" ), Iconos.TB_Arriba(), "arriba" ), None,
                        ( tr( "ABAJO" ), Iconos.TB_Abajo(), "abajo" ), None,
                    ]
        tb = Controles.TB( self, liAcciones )
        tb.setFont( flb )

        ly = Colocacion.V().control(tb).control(self.grid)
        gb = Controles.GB(self,tr("TUT_VARIABLES_GLOBALES"),ly ).ponFuente( f )

        # Layout
        layout = Colocacion.H().control(gb)
        self.setLayout( layout )

    #--------------------------------------------------------------------------------------------------------------------------------
    def gridNumDatos( self, grid ) :
        return len(self.liVariables)

    #--------------------------------------------------------------------------------------------------------------------------------
    def gridDato( self, grid, fila, oColumna ) :
        clave = oColumna.clave
        if clave == "NUMERO" :
            return str(fila+1)
        elif clave == "NOMBRE" :
            return self.liVariables[fila].nombre
        elif clave == "TIPO" :
            return self.dicTipos[self.liVariables[fila].tipo]

        elif clave == "INICIAL" :
            return str(self.liVariables[fila].inicial)

    #--------------------------------------------------------------------------------------------------------------------------------
    def gridDobleClick( self, grid, fila, oColumna ) :
        self.modificar()

    #--------------------------------------------------------------------------------------------------------------------------------
    def procesarTB( self ) :
        accion = self.sender().clave
        eval( "self.%s()"%accion )

    #--------------------------------------------------------------------------------------------------------------------------------
    def mas( self ) :
        menu = Controles.LMenu()

        f = Controles.TipoLetra( puntos=8, peso=75 )
        menu.ponFuente( f )

        for txt, clave in tipoVariables() :
            menu.opcion( clave, txt, Iconos.PuntoAzul() )

        resp = menu.lanza()
        if resp is not None :
            w = WET_Variable(self, -1, self.liVariables, resp )
            if w.exec_() :
                regVariable = w.regVariable
                regVariable.id = self.tutorial.idNuevo()
                self.liVariables.append( regVariable )
                self.grid.refresh()
                self.grid.gobottom()
                self.grid.setFocus()

    #--------------------------------------------------------------------------------------------------------------------------------
    def borrar( self ) :
        fila = self.grid.recno()
        if fila >= 0 :
            if QTUtil2.pregunta( self, tr( "TUT_BORRAMOS_VARIABLE", self.liVariables[fila].nombre )) :
                del self.liVariables[fila]
                self.grid.refresh()
                self.grid.setFocus()

    #--------------------------------------------------------------------------------------------------------------------------------
    def modificar( self ) :
        fila = self.grid.recno()
        if fila >= 0 :
            w = WET_Variable(self, fila, self.liVariables)
            if w.exec_() :
                self.liVariables[fila] = w.regVariable
                self.grid.refresh()
                self.grid.setFocus()

    #--------------------------------------------------------------------------------------------------------------------------------
    def siEstaNombre( self, nombre ) :
        for rf in self.liVariables :
            if rf.nombre == nombre :
                return True
        return False

    #--------------------------------------------------------------------------------------------------------------------------------
    def arriba( self ) :
        fila = self.grid.recno()
        if fila > 0 :
            self.liVariables[fila-1],self.liVariables[fila] = self.liVariables[fila],self.liVariables[fila-1]
            self.grid.goto(fila-1,0)
            self.grid.refresh()
            self.grid.setFocus()

    #--------------------------------------------------------------------------------------------------------------------------------
    def abajo( self ) :
        fila = self.grid.recno()
        if fila >= 0 and fila < (len(self.liVariables)-1) :
            self.liVariables[fila+1],self.liVariables[fila] = self.liVariables[fila],self.liVariables[fila+1]
            self.grid.goto(fila+1,0)
            self.grid.refresh()
            self.grid.setFocus()
