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

import os
import shutil
import urllib
import zipfile
from PySide import QtCore, QtGui

from Code.Traducir import tr

import Code.Util as Util

import Code.GM as GM

import QTUtil2
import Colocacion
import Iconos
import Controles

import Grid
import Columnas

# --------------------------------------------------------------------------------------------------------
class WGM( QtGui.QDialog ):

    def __init__(self, procesador )  :

        wParent = procesador.pantalla
        self.configuracion = procesador.configuracion
        self.procesador = procesador

        super(WGM, self).__init__(wParent)

        self.setWindowTitle( tr("JUEGA_GRANMAESTRO" ) )
        self.setWindowIcon( Iconos.GranMaestro() )
        self.setWindowFlags( QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint )

        self.setMinimumWidth( 450 )

        # Toolbar
        liAcciones = [  ( tr( "ACEPTAR" ), Iconos.TB_Aceptar(), "aceptar" ), None,
                        ( tr( "CANCELAR" ), Iconos.TB_Cancelar(), "cancelar" ), None,
                        ( tr( "GM_IMPORTAR" ), Iconos.TB_ImportarGM(), "importar" ), None,
                    ]
        tb = Controles.TB( self, liAcciones )

        flb = Controles.TipoLetra( puntos=10 )

        self.rbBlancas = QtGui.QRadioButton( tr( "PGN_WHITE" ) )
        self.rbBlancas.setChecked( True )
        self.rbNegras = QtGui.QRadioButton( tr( "PGN_BLACK" ) )
        self.rbNegras.setChecked( False )

        # GM
        self.liGM = GM.listaGM()
        self.cbGM = QTUtil2.comboBoxLB( self.liGM, self.liGM[0][1] )

        self.chContrario = Controles.CHB( tr( "GM_JUGCONTRARIO" ), False )

        self.edJugInicial, lbInicial = QTUtil2.spinBoxLB( 1, 1, 99, etiqueta=tr("JUGADA_INICIAL"), maxTam = 40 )

        # Juez
        self.liMotores = self.configuracion.comboMotoresMultiPV20()
        self.cbJmotor, self.lbJmotor = QTUtil2.comboBoxLB( self.liMotores, self.configuracion.tutorInicial, tr( "MOTOR" ) )
        self.edJtiempo = Controles.ED( self ).tipoFloat().ponFloat( 1.0 ).anchoFijo(50)
        self.lbJtiempo = Controles.LB( tr( "TIEMPO_SEGUNDOS" ) + " :" )
        self.chMostrar = Controles.CHB( tr( "MOSTRAR_VALORACION" ), True )

        hbox = Colocacion.H().relleno(1).control(self.rbBlancas).espacio(10).control(self.rbNegras).relleno(1)
        gbColor = Controles.GB( self, tr( "JUGAMOS_CON" ), hbox ).ponFuente( flb )

        hbox = Colocacion.H().relleno(1).control(self.cbGM).relleno(1)
        gbGM = Controles.GB( self, tr( "GM_ELIGE" ), hbox ).ponFuente( flb )

        ## Tiempo
        ly1 = Colocacion.H().control( self.lbJmotor ).control( self.cbJmotor ).relleno(1)
        ly2 = Colocacion.H().control( self.lbJtiempo ).control( self.edJtiempo ).relleno(1)
        ly = Colocacion.V().otro( ly1 ).otro( ly2 ).control( self.chMostrar )
        gbJ = Controles.GB( self, tr( "JUEZ" ), ly ).conectar( self.cambiaJuez )
        self.gbJ = gbJ

        ## Inicial
        lyInicial = Colocacion.H().relleno(1).control(lbInicial).control(self.edJugInicial).relleno(1)

        vlayout = Colocacion.V().control(gbColor).espacio(5).control( gbGM ).espacio(5).control(gbJ).espacio(5)
        vlayout.control( self.chContrario ).otro(lyInicial).margen( 20 )

        layout = Colocacion.V().control( tb ).otro( vlayout ).margen( 3 )

        self.setLayout( layout )

        self.recuperaDic()
        self.cambiaJuez()

    def procesarTB( self ) :
        accion = self.sender().clave
        if accion == "aceptar" :
            self.gm = self.cbGM.resultado()
            self.siBlancas = self.rbBlancas.isChecked()
            self.siJuez = self.gbJ.isChecked()
            self.motor = self.cbJmotor.resultado()
            self.tiempo = int(self.edJtiempo.textoFloat()*10)
            self.mostrar = self.chMostrar.isChecked()
            self.jugContrario = self.chContrario.isChecked()
            self.jugInicial = self.edJugInicial.valor()
            if self.siJuez and self.tiempo == 0 :
                self.siJuez = False
            self.grabaDic()
            self.accept()
        elif accion == "cancelar" :
            self.reject()
        elif accion == "importar" :
            if importarGM( self ) :
                liC = GM.listaGM()
                self.cbGM.clear()
                for tp in liC :
                    self.cbGM.addItem( tp[0], tp[1] )
                self.cbGM.setCurrentIndex( 0 )

    def cambiaJuez( self ) :
        si = self.gbJ.isChecked()
        for control in ( self.cbJmotor, self.lbJmotor,self.edJtiempo, self.lbJtiempo, self.chMostrar ) :
            control.setVisible( si )

    def grabaDic( self ) :
        dic = {}

        dic[ "GM" ] = self.gm
        dic[ "SIBLANCAS" ] = self.siBlancas
        dic[ "SIJUEZ" ] = self.siJuez
        dic[ "MOTOR" ] = self.motor
        dic[ "TIEMPO" ] = self.tiempo
        dic[ "MOSTRAR" ] = self.mostrar
        dic[ "JUGCONTRARIO" ] = self.jugContrario
        dic[ "JUGINICIAL" ] = self.jugInicial

        Util.guardaDIC( dic, self.configuracion.ficheroGM )

    def recuperaDic( self ) :
        dic = Util.recuperaDIC( self.configuracion.ficheroGM )
        if dic :
            gm = dic[ "GM" ]
            siBlancas = dic[ "SIBLANCAS" ]
            siJuez = dic[ "SIJUEZ" ]
            motor = dic[ "MOTOR" ]
            tiempo = dic[ "TIEMPO" ]
            mostrar = dic[ "MOSTRAR" ]
            jugContrario = dic.get( "JUGCONTRARIO", False )
            jugInicial = dic.get( "JUGINICIAL", 1 )

            for n, v in enumerate(self.liGM) :
                if v[1] == gm :
                    self.cbGM.setCurrentIndex( n )
                    break

            self.rbBlancas.setChecked(siBlancas)
            self.rbNegras.setChecked(not siBlancas)

            self.gbJ.setChecked(siJuez)

            for n, v in enumerate(self.liMotores) :
                if v[1] == motor :
                    self.cbJmotor.setCurrentIndex( n )
                    break

            self.edJtiempo.ponFloat(float(tiempo/10.0))

            self.chMostrar.setChecked(mostrar)

            self.chContrario.setChecked(jugContrario)

            self.edJugInicial.ponValor( jugInicial )

# --------------------------------------------------------------------------------------------------------
def eligeJugada( gestor, liJugadas, siGM ) :
    menu = Controles.LMenu(puntos=10)

    if siGM :
        titulo = gestor.nombreGM
        icono = Iconos.GranMaestro()
    else :
        titulo = tr( "RIVAL" )
        icono = Iconos.Carpeta()
    menu.opcion( None, titulo, icono )
    menu.separador()

    icono = Iconos.PuntoAzul() if siGM else Iconos.PuntoNaranja()

    for desde, hasta, coronacion, rotulo, pgn in liJugadas :

        if rotulo and (len(liJugadas) > 1) :
            txt = "%s - %s"%( pgn, rotulo )
        else :
            txt = pgn
        menu.opcion( (desde,hasta,coronacion), txt, icono )
        menu.separador()

    resp = menu.lanza()
    if resp :
        return resp
    else :
        desde, hasta, coronacion, rotulo, pgn = liJugadas[0]
        return (desde, hasta, coronacion)

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

    def __init__( self, wParent, liGM ) :

        super(WImportar, self).__init__(wParent)

        self.liGM = liGM

        self.setWindowTitle(  tr( "GM_IMPORTAR" ) )
        self.setWindowIcon( Iconos.TB_ImportarGM() )
        self.setWindowFlags( QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint)

        # Toolbar
        liAcciones = [  ( tr( "GM_IMPORTAR" ), Iconos.TB_Aceptar(), "aceptar" ), None,
                        ( tr( "CANCELAR" ), Iconos.TB_Cancelar(), "cancelar" ), None,
                        ( tr( "GM_MARCAR" ), Iconos.TB_Marcar(), "marcar" ), None,
                    ]
        tb = Controles.TB( self, liAcciones )

        # Lista
        oColumnas = Columnas.ListaColumnas()
        oColumnas.nueva( "ELEGIDO", "", 22, siChecked = True )
        oColumnas.nueva( "NOMBRE", tr( "GM_GM" ), 140 )
        oColumnas.nueva( "PARTIDAS", tr( "GM_PARTIDAS" ), 60, siDerecha = True )

        self.grid = Grid.Grid( self, oColumnas )
        n = self.grid.anchoColumnas()
        self.grid.setFixedWidth( n + 20 )

        # Layout
        layout = Colocacion.V().control(tb).control(self.grid).margen( 3 )
        self.setLayout( layout )

    #--------------------------------------------------------------------------------------------------------------------------------
    def procesarTB( self ) :
        accion = self.sender().clave
        if accion == "aceptar" :
            self.accept()
        elif accion == "cancelar" :
            self.reject()
        elif accion == "marcar" :
            self.marcar()

    #--------------------------------------------------------------------------------------------------------------------------------
    def marcar( self ) :
        menu = Controles.LMenu()
        f = Controles.TipoLetra( puntos=8, peso=75 )
        menu.ponFuente( f )
        menu.opcion( 1, tr("GM_MARCARTODOS"), Iconos.PuntoVerde() )
        menu.opcion( 2, tr("GM_MARCARNINGUNO"), Iconos.PuntoNaranja() )
        resp = menu.lanza()
        if resp :
            for obj in self.liGM :
                obj["ELEGIDO"] = resp == 1
            self.grid.refresh()

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

    #--------------------------------------------------------------------------------------------------------------------------------
    def gridPonValor( self, grid, fila, columna, valor ) :
        self.liGM[fila][columna.clave] = valor

    #--------------------------------------------------------------------------------------------------------------------------------
    def gridDato( self, grid, fila, oColumna ) :
        return self.liGM[fila][oColumna.clave]

#==========================================================================================================================================
def importarGM( ownerGM ) :
    # Primero nos tenemos que traer la lista de la web
    fichz = "_listaGM.zip"
    ficht = "_listaGM.txt"
    fichtg = "gm/listaGM.txt"
    try :
        os.remove( ficht )
    except :
        pass
    web = ownerGM.procesador.web
    me = QTUtil2.mensEspera.inicio( ownerGM, tr( "GM_LEYENDO" ) )
    siError = False
    try :
        urllib.urlretrieve( "%s/gm/%s"%(web,fichz), fichz )
        zfobj = zipfile.ZipFile(fichz)
        for name in zfobj.namelist():
            outfile = open(name, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()
        zfobj.close()
        os.remove( fichz )
    except :
        siError = True
    me.final()

    if siError :
        QTUtil2.mensError( ownerGM, tr( "GM_NOLISTA" ) )
        return False

    shutil.copy( ficht, fichtg )
    os.remove( ficht )

    f = open( fichtg, "rb" )
    liGM = []
    for linea in f :
        linea =linea.strip()
        if linea :
            gm, nombre, ctam, cpart = linea.split( "·" )
            tam = int(ctam)
            dic = { "GM":gm, "NOMBRE":nombre, "PARTIDAS":cpart , "ELEGIDO" : False}
            siMas = True
            if os.path.isfile( "gm/%s.gmw"%gm ) :
                t = 0
                for x in "bwi" :
                    t += os.stat("gm/%s.gm%s"%( gm, x )).st_size
                siMas = t != tam
            if siMas :
                liGM.append( dic )
    f.close()

    if len(liGM) == 0 :
        QTUtil2.mensaje( ownerGM, tr( "GM_NOMASGM" ) )
        return False

    w = WImportar( ownerGM, liGM )
    if w.exec_() :
        for dic in liGM :
            if dic["ELEGIDO"] :
                gm = dic["GM"]
                gm = gm[0].upper() + gm[1:].lower()
                me = QTUtil2.mensEspera.inicio( ownerGM, tr( "GM_IMPORTANDO", gm ), opacity = 1.0 )

                #Descargamos
                fzip = gm + ".zip"
                urllib.urlretrieve( "%s/gm/%s.zip"%(web,gm), fzip )

                zfobj = zipfile.ZipFile(fzip)
                for name in zfobj.namelist():
                    outfile = open("gm/%s"%name, 'wb')
                    outfile.write(zfobj.read(name))
                    outfile.close()
                zfobj.close()
                os.remove( fzip )

                me.final()

        return True

    return False

