from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.mtemplates import env_theme, PTemplate
from cuchulu.modules.admin.models.admin import UserAdmin, LoginTries
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.libraries.db import simplequery
from settings import config
from cuchulu.libraries.datetime import now, format_local_strtime, timestamp_to_datetime, obtain_timestamp
from cuchulu.libraries.keyutils import create_key_encrypt, create_key
from time import time
from bottle import request, redirect
from cuchulu.libraries.db.formsutils import check_form, csrf_token
from cuchulu.libraries.db.coreforms import PasswordForm
from cuchulu.libraries.sendmail import SendMail

login_tries=5

if hasattr(config, 'login_tries'):
    login_tries=config.login_tries

seconds_login=300

if hasattr(config, 'seconds_login'):
    seconds_login=config.seconds_login


def check_login_tries(db):
    
    logintries=LoginTries(db)
    
    logintries.safe_query()
    
    ip=request.environ.get('X-REAL-IP') or request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
    
    """
    if 'x-real-ip' in request.headers:
        ip=request.headers['x-real-ip']
    elif 'x-forwarded-for' in request.headers:
        ip=request.headers['x-forwarded-for']
    else:
        ip=request.client.host
    """

    you_cannot_login=0
    
    now_str=now()
    date_now=format_local_strtime('YYYY-MM-DD HH:mm:ss', now_str)
    
    date_check=format_local_strtime('YYYY-MM-DD HH:mm:ss', timestamp_to_datetime(obtain_timestamp(now_str)-seconds_login))
    
    logintries.query('delete from logintries2 where last_login<%s', [date_check])
    
    arr_try=logintries.set_conditions('WHERE ip=%s', [ip]).select_a_row_where()
    
    if arr_try:
        
        if arr_try['num_tries']<login_tries:
        
            logintries.query('update logintries2 set num_tries=num_tries+1, last_login=%s WHERE ip=%s', [date_now, ip])
            
        else:
            
            you_cannot_login=1
            
    else:
        
        logintries.query('insert into logintries2 (`ip`, `num_tries`, `last_login`) VALUES (%s, %s, %s)', [ip, 1, date_now])

    return you_cannot_login
