#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      Antonio Barbosa
#
# Created:     24/03/2023
# Copyright:   (c) Antonio Barbosa 2023
# Licence:     <your licence>
#-------------------------------------------------------------------------------



from time import time
START_TIME=time()

print ('------------------- Python start.py 3--------------')
from browser import window ,document
from browser import ajax
from browser import html #para gerar wigets on the fly
from browser import timer
from jqueryui import jq as jqui
import json


#------------------------------------------------------------------------
def abint(s):
    try:
        #primerio vai remover separador milhar:
        s=s.replace(',','')
        return int(s)
    except:
        return 0


##def onDateClosed(s,obj):
##    print ("onDateClosed %s" %s)
##
##
##jqui['data'].datepicker(
##        changeMonth=True
##        ,changeYear=True
##        ,dateFormat= "yy-mm-dd"
##        ,monthNamesShort  =["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"]
##        ,showButtonPanel=True
##        ,onClose=onDateClosed
##        ,closeText= "Fechar"
##        )


def ablog(mess,a='',b=''):
    #def time():
    #    return float(window.Date.now.getTime() / 1000)

    #time=window.Date.now()
    #print (time(),mess,a,b)
    #print (time(),mess,a,b)
    print ('============>',int(time()-START_TIME),mess,a,b)

def onLoginKey(ev):
    #print ('onLoginKey')
    if ev.charCode==13:   #13  o firefox não reconhece char 13!
        if document["login_username"].value!='':
            if document["login_password"].value!='':
                onButton('login')

#---------------------------- BUTTONS: --------------------------------------------------------

def pedido_ajax(D):
        req = ajax.ajax()
        p='on_complete_%s'%D['op']
        func=globals()[p]
        req.bind('complete',func)
        req.open('POST',"pedidos_ajax",True)
        req.set_header('content-type','application/x-www-form-urlencoded')
        req.send(D)


def onButton(op):
    print ("onButton:" ,op)

    if op=='get_list': #
        numero=document['numero'].value
        if abint(numero)<1:
            numero=1
        limite=document['limit'].value
        if abint(limite)<1:
            limite=1
        pedido_ajax({'op':op,
        'numero':numero,
        'limite':limite,
         })
        return
    elif op=='update_list': #
        numero=document['numero'].value
        if abint(numero)<1:
            numero=1
        limite=document['limit'].value
        if abint(limite)<1:
            limite=1
        pedido_ajax({'op':op,
        'numero':numero,
        'limite':limite,
         })
        return
    elif op=="login":
        pedido_ajax({'op':op,
        "login_username":document["login_username"].value,
        "login_password":document["login_password"].value,
         })
        return
    elif op=="login_ab":
        pedido_ajax({'op':'login',
        "login_username":'ab',
        "login_password":'ab',
         })
        return
    elif op=="showtables": #
        req = ajax.ajax()
        pedido_ajax({'op':op,
         })
        return
    elif op=="execsql": #
        sql=document['sql'].value
        print (sql)
        if len(sql)==0:
            return
        req = ajax.ajax()
        pedido_ajax({'op':op,
        'sql':sql,
         })
        return
    elif op=="describe_tabela": #changesel tabelas
        req = ajax.ajax()
        pedido_ajax({'op':op,
        'tabela':document['tabelas'].value,
         })
        return

    elif op=="viewlog": #
        req = ajax.ajax()
        pedido_ajax({'op':op,
         })
        return
    elif op=="viewlog2": #
        req = ajax.ajax()
        pedido_ajax({'op':op,
        'cmd':'tail  -n 100 /var/log/apache2/cobra1.flsb.net_error.log',
         })
        return
    elif op=="logoff": #
        req = ajax.ajax()
        pedido_ajax({'op':op,
         })
        return
    elif op=="TestPage":
        #ablog ("TestPage...")
        pass
    elif op=="Refresh": #depois de login
        print ("Refresh. ---> Vai fazer submit:" ,op)
        document["mySubmit"].value=op #para informar a pag pretendida
        document["myForm"].submit()
    else:  #NÃO DEVE ACONTECER!
        alert("onButton: %s" %op)
##    if erro:
##        alert(erro)
##        return
##
##    print ("onButton. ---> Vai fazer submit:" ,op)
##    document["mySubmit"].value=op #para informar a pag pretendida
##    document["myForm"].submit()


def on_complete_login(req):
    try:
        print ('---> on_complete_login')
        if req.status==200 or req.status==0:
            if len(req.text):
                ok=json.loads(req.text)
                print ('resposta-->',ok)
                if ok=='true' or ok==True :  #com brython 3.7 retorna True!!!!!
                    login_dialog.dialog("close")
                    onButton("Refresh")#não está a fazer nada ...
                else:
                    ablog ("ERRO no LOGIN. Resposta=",ok)
                    message("Login Errado. Por favor, confira Nome e Password",timeout=3000)

    except Exception as error:
        ablog ("CompleteLogin  ERRO [%s] "%str(error))

def on_complete_viewlog(req):
    P=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    showTable(P,False)

def on_complete_viewlog2(req):
    if req.status==500:
        alert(req.text)
        return
    result=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    P={}
    P['headers']=['Time','Report']
    P['data']=[]
    lines=result.split('\\n')
    for line in lines:
        p=line.rfind(']')
        if p>104:
            p=104
        d=[line[12:20],line[p+1:]]
        P['data'].append(d)
    showTable(P,False)


def on_complete_logoff(req):
    print ('oncompletelogoff')
    try:
        if req.status==200 or req.status==0:
            if len(req.text):
                ok=json.loads(req.text)
                document["HomeForm"].submit() #vai fazer Reload

    except Exception as error:
        ablog ("CompleteLoggOff  ERRO [%s] "%str(error))

def on_complete_get_list(req):

    P=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    showTable(P,True)

def on_complete_describe_tabela(req):
    if req.status==500:
        alert(req.text)
        return
    P=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    showTable(P,True)

def on_complete_showtables(req):
    print ("on_complete_showtables")
    print (req.status)
    ##        if req.status==200 or req.status==0:
    result=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    document['tabelas'].clear()
    document['tabelas']<= html.OPTION('-Tabelas-',value=-1)
    for s in result:
        document['tabelas'] <= html.OPTION(s,value=s)

def on_complete_execsql(req):
    print ("on_complete_execsql")
    print (req.status)
    if req.status==500:
        alert(req.text)
        return
    ##        if req.status==200 or req.status==0:
    result=json.loads(req.text)#, object_pairs_hook=OrderedDict)
    print (result)
    document['mess'].value=result

def on_complete_update_list(req):
    try:
        print ("on_complete update list")
        #print (req.text)
        P=json.loads(req.text)#, object_pairs_hook=OrderedDict)

    except Exception as error:
        print ("ERRO  on_complete update list :%s"%str(error))


def onchange_sel(ev):
    try:

        item=ev.srcElement
        #print ("onchange_sel ",item)
        if item.id=="tabelas":
            onButton('describe_tabela')
        else:
            pass


    except Exception as error:
        print ("ERRO [%s] on_changesel "%str(error))



#--------------------- Utilitários -----------------------------------

def Test(ev):
    ablog ("Test...")

def showTable(P,Edit=False):

    document['div_list'].clear()   # erase initial content
    document['div_list'].contentEditable="false"

    headers= (P['headers'])
    table = html.TABLE()
    table.class_name="TableMapa"
    row = html.TR() # create a row
    for s in headers:
        h=html.TH(s)
        h.class_name="table_head"  #para bind sort
        row <= h
    table <= row # add the row to the table
    for E in P['data']:
        linha=""
        for s in E:
            x=str(s)
            cell=html.TD(x)
            cell.class_name="table_cell"
            linha+=cell
        row = html.TR()# add a row
        row.class_name="RowTable"
        row<= linha
        table <= row
    document['div_list'] <= table    # insert table in the element
    if Edit==True:
        document['div_list'].contentEditable="true"

def alert(mess,title=u"Atencao!!"):
    #print ("myalert: "+mess)
    global alert_dialog
    #document["alert_dialog"].text=mess
    document["alert_dialog"].html=mess  #html em vez de text para poder mostrar <br>
    alert_dialog = jqui["alert_dialog"].dialog(
    modal=True
    ,title=title #.encode("utf-8")
    ,buttons={"OK": closeAlertDialog}
    ,closeOnEscape=True
    )

def closeAlertDialog(ev):
    #print ("closeAlertDialog")
    global alert_dialog
    alert_dialog.dialog("close")


def message(mess,title="Atenção!",level=0,timeout=6000):
    print ('--------- Message ----------')
    print (mess)
    print ('--------- Message ----------')

    global mess_dialog
    if mess_dialog:
        hide_dialog()

    document["mess_dialog"].text=mess
    if len(mess)>100:
        document["mess_dialog"].style = { "font-family": "Arial",    "font-size": "20px"}

    mess_dialog=jqui['mess_dialog'].dialog(dialogClass="no-titlebar",minHeight=50,minWidth=500)
    timer.set_timeout(hide_dialog, timeout)



def hide_dialog():
    try:
        global mess_dialog
        mess_dialog.dialog('destroy')
        mess_dialog=None
    except:
        pass

def refresh_user():
    print ("refresh_user")
    for s in ['logoff','viewlog','viewlog2','showtables','get_list','update_list','execsql']:
        document[s].bind('click', lambda ev,op=s:onButton(op))
    #document['logoff'].bind('click', lambda ev,op="logoff":onButton(op))
    document['tabelas'].bind('change', onchange_sel)

alert_dialog=None
mess_dialog=None


#aqui dá erro: Javascript error RangeError: Maximum call stack size exceeded
#if len(document["username"].value):
if len(document["username"].text):
    print ("--------------------------------------- Username: %s"%document["username"].text)
    refresh_user()
else:
    print ('--------------------------------------- Sem username: Vai activar login_dialog')

    document['login_ok'].bind('click', lambda ev,op="login":onButton(op))
    document['login_ab'].bind('click', lambda ev,op="login_ab":onButton(op))
    document["login_username"].bind('keypress', lambda ev:onLoginKey(ev))
    document["login_password"].bind('keypress', lambda ev:onLoginKey(ev))
    #com brython 3.7 ao invocar o dialog não se pode passar parametros! dá erro: Javascript exception: RangeError: Maximum call stack size exceeded
    #login_dialog=jq['login_dialog'].dialog(title="COLABORAÇÕES Autenticação",width=340, height= 160,dialogClass= 'no-close login-dialog')
    title=u"AutenticaÃ§Ã£o"#.encode('utf-8')
    login_dialog=jqui['login_dialog'].dialog(title=title,width=340, height= 200,dialogClass= 'no-close login-dialog')
    print ('default_username: ',document['default_username'].value)
    document['login_username'].value= document['default_username'].value

