from modules.cuchulublog import cuchulublog_app
from flask import request, g, url_for
from settings import config
from paramecio2.libraries.mtemplates import PTemplate, env_theme
from paramecio2.libraries.i18n import I18n
from modules.blog.models.blog import Post
from paramecio2.libraries.plugins import db
from paramecio2.libraries.pages import Pages
from paramecio2.libraries.db.extrafields.emailfield import EmailField
import requests
from paramecio2.libraries.sendmail import SendMail
from paramecio2.libraries.urls import make_media_url

try:
    import ujson as json
except:
    import json

secret_captcha='6LcFDSgUAAAAANAF2t513zIhpAZYpEbHCpmIkIV9'

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

email_used='antonio.delarosa@coesinfo.com'
email_send='antonio.delarosa@coesinfo.com'

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

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


env=env_theme(__file__)

t=PTemplate(env)

#t.env.directories=admin_t.env.directories

#t.env.directories.insert(1, os.path.dirname(__file__).replace('/admin', '')+'/templates/admin')

@cuchulublog_app.route('/home')
def cuchulublog_home():

    return t.load_template('home.phtml', title=I18n.lang('cuchulublog', 'home', 'Home'))
    
@cuchulublog_app.route('/blog/<path:date>/<slugify>/<int:post_id>')
def cuchulublog_blog(date, slugify, post_id):
    
    return t.load_template('post.phtml', title=I18n.lang('cuchulublog', 'post', 'Post'), post_id=post_id)


@cuchulublog_app.route('/projects')
def cuchulublog_projects():

    return t.load_template('projects.phtml', title=I18n.lang('cuchulublog', 'projects', 'Projects'))


@cuchulublog_app.route('/blog')
@db
def cuchulublog_all_posts():

    post=Post(g.connection)
    
    try:
        begin_post=request.args.get('begin_post', 0)
        
    except:
        begin_post=0
        
    total_elements=post.select_count()
    
    num_elements=10
    
    q=post.query('select * from post order by date DESC limit %s, 10', [begin_post])

    arr_post=[]

    lang_default=I18n.default_lang

    for row in q:

        row['date']=str(row['date']).replace(' 00:00:00', '').replace('-', '/')
        row['title']=json.loads(row['title'])[lang_default]
        
        row['text']=json.loads(row['text'])[lang_default]
        
        arr_post.append(row)
    
    html_pages=Pages.show(begin_post, total_elements, num_elements, url_for('.cuchulublog_all_posts'), initial_num_pages=20, variable='begin_page', label='', func_jscript='')
    
    return t.load_template('blog.phtml', title=I18n.lang('cuchulublog', 'blog_last_post', 'Blog - lasts posts'), posts=arr_post)

@cuchulublog_app.route('/contact')
def cuchulublog_contact():
    
    return t.load_template('contact.phtml', title=I18n.lang('cuchulublog', 'contact', 'Contact'))
    
@cuchulublog_app.route('/send_contact', methods=['POST'])
def send_contact():

    #p=GetPostFiles()
    
    #p.obtain_post()
    
    email_check=EmailField('email')

    nombre=request.form.get('nombre', '').strip()
    email=request.form.get('email', '').strip()
    email=email_check.check(email)
    #telefono=request.form.get('telefono', '').strip()
    asunto=request.form.get('asunto', '').strip()
    texto=request.form.get('texto', '').strip()

    ip = request.headers.get('HTTP_X_FORWARDED_FOR') or request.remote_addr
        
    r=requests.post('https://www.google.com/recaptcha/api/siteverify', data = {'secret': secret_captcha, 'response': request.form['g-recaptcha-response'], 'remoteip': ip})

    response_json=r.json()

    arr_return={'error': 1, 'txt_error': 'Error: no se pudo enviar el email, vuelva a intentarlo', 'form': {}}

    text=t.load_template('email/content_contact.phtml', nombre=nombre, email=email, asunto=asunto, texto=texto)
    """
    text.="<h1>FORMULARIO DE CONTACTO</h1>\n";

    $text.="<p>Nombre: %s</p>\n\n" % nombre
    $text.="<p>E-mail: %s</p>\n\n" % email
    $text.="<p>Asunto: %s</p>\n\n" % asunto
    $text.="<p>Texto: \n\n%s</p>\n" % texto
    """
    
    if nombre!='' and asunto!='' and texto!='' and email!='' and response_json['success']:

        sendmail=SendMail()
        
        image_url=make_media_url('images/logo.png', 'cuchulublog')
        
        email_text=t.load_template('email/email.phtml', text=text, logo_url=image_url)

        if sendmail.send(email_used, [email_send], 'Cuchulu.com - %s' % asunto, email_text, content_type='html', attachments=[]):
            
            return {'error': 0, 'txt_error': ''}

    if asunto=='':
        arr_return['form']['asunto']='Error: se necesita un asunto'

    if texto=='':
        arr_return['form']['texto']='Error: se necesita un texto'

    if email=='':
        arr_return['form']['email']='Error: se necesita un email correcto'

    if nombre=='':
        arr_return['form']['nombre']='Error: se necesita un nombre'

    if not response_json['success']:
        arr_return['form']['captcha']='Error: captcha vacio'

    return arr_return

    
@cuchulublog_app.route('/about')
def cuchulublog_about():
    
    return t.load_template('about.phtml', title=I18n.lang('cuchulublog', 'about', 'About'))
    
if config.default_module=="cuchulublog":

    home=cuchulublog_app.route("/")(cuchulublog_home)
