
from flask import Flask, render_template, jsonify, send_file, url_for
import os
from pprint import pprint

# from py_funcs.db_connect import DB # esta la debes de eliminar
from db_xala_dev.db_sqlite import DBSQLite
from db_xala_dev.views import v

# INTEGRAR EL USO DE CACHE
from flask_caching import Cache

# from py_funcs.confs import ext

# export n_server="Servidor No. X";
n_server = os.getenv("n_server")

app = Flask(__name__)

import platform


db_path = None

if 'microsoft' in platform.uname().release.lower():
    db_path = os.path.join(os.getcwd(), "db_xala_dev/xala_dev.db")
elif platform.system() == "Linux":
    db_path = "/var/www/xala.dev/db_xala_dev/xala_dev.db"
    
DB = DBSQLite(db_path)

@app.route('/')
def home():
    q_dataHome = 'SELECT pk, label, svg_data FROM home where pk <> "data analytics";'
    # q_dataHome = "SELECT pk, label, svg_data FROM home;"
    dataHome = DB.get_data(q_dataHome)
    return render_template(v['home'], dataHome=dataHome, n_server=n_server)

@app.route('/latest-posts')
def latest_posts():
    q_last_data = "SELECT id, pk, titulo_tema FROM ALL_POSTS ORDER BY id DESC LIMIT 7;"
    last_data = DB.get_data(q_last_data)
    return jsonify(last_data)


@app.route('/section/<subseccion_name>')
def subseccion(subseccion_name):
    
    q_cur_ext = f"SELECT ext FROM exts WHERE pk = '{subseccion_name}';"
    cur_ext = DB.get_data(q_cur_ext)[0][0]
    
    q_dataHome = f"SELECT * FROM home WHERE pk = '{subseccion_name}';"
    dataHome = DB.get_data(q_dataHome)
    
    q_db_subtemas = f"SELECT id, pk, titulo_tema, sintesis FROM all_posts WHERE pk = '{subseccion_name}';"
    db_subtemas = DB.get_data(q_db_subtemas)

    return render_template(v['seccion'], dataHome=dataHome, db_subtemas=db_subtemas, cur_ext=cur_ext, subseccion_name=subseccion_name)

@app.route('/section/<subseccion_name>/tema/<index_tema>')
def subseccion_tema(subseccion_name, index_tema):

    # retorna la extensión para ruta actual del usuario (eje. cat file.txt)
    q_cur_ext = f"SELECT ext FROM exts WHERE pk = '{subseccion_name}';"
    cur_ext_base = DB.get_data(q_cur_ext)[0][0]

    # obtener solo la información necesaria de la base de datos
    # me quede en esta línea, debes de borrar la columna html_template
    q_data = f"SELECT date, status, titulo_tema, html_alert, lst_glosary, lst_post_related FROM all_posts WHERE pk = '{subseccion_name}' AND id = {index_tema};"
    data = DB.get_data(q_data)
    
    # información del glosario
    lst_glosary = [str(ele).strip() for ele in data[0][4].split(',')]
    
    # el alerta, para que tipo de sistema es aplicable la nota
    alert= 'no_template' if f'{data[0][3]}' == 'nan' else f'{data[0][3]}'

    # notas relacionadas
    f_lst_glosary = [DB.get_data(f"SELECT * FROM glosary WHERE pk = '{str(ele).strip()}'") for ele in lst_glosary]
    
    links_related = f'{data[0][5]}'.split(',')
    if links_related[0] != 'None':
        links_lambda = lambda x: f"SELECT pk, id, titulo_tema  FROM all_posts WHERE id = {int(f'{x}'.strip())};" 
        f_lst_data_links = [DB.get_data(links_lambda(id))[0] for id in links_related]
    else: 
        f_lst_data_links = []
    
    cat_file = f'cat f_{subseccion_name}_{index_tema}'

    template_path=f'html_template/{index_tema}.html'

    return render_template(v['tema'], data=data, cur_ext_base=cur_ext_base, subseccion_name=subseccion_name, f_lst_glosary=f_lst_glosary, f_lst_data_links=f_lst_data_links, cat_file=cat_file, alert=alert, template_path=template_path)
    
      

@app.route('/more-info/about-me')
def about_me():
    data = DB.get_data('SELECT * FROM about_me;')
    lst_glosary = data[0][1].split(", ")
    f_lst_glosary = [DB.get_data(f"SELECT * FROM glosary WHERE pk = '{str(ele).strip()}'") for ele in lst_glosary]
    
    return render_template(v['m.i.']['me'], data=data, f_lst_glosary=f_lst_glosary)
    

@app.route('/more-info/all-posts')
def all_posts():

    q_final = '''    
    SELECT DISTINCT a.pk, e.name FROM all_posts a
    INNER JOIN exts e ON e.pk = a.pk ;
    '''
    final = DB.get_data(q_final)

    q = '''
    SELECT AP.id, AP.pk, AP.date, AP.titulo_tema, AP.sintesis, H.icon
    FROM ALL_POSTS AP
    INNER JOIN home H ON AP.PK = H.PK;
    '''
    db_newPosts = DB.get_data(q)
    return render_template(v['m.i.']['np'], db_newPosts=db_newPosts, db_mainSections=final)

@app.route('/more-info/projects')
def projects():
    return render_template(v['m.i.']['pjs'])

@app.route('/more-info/cv')
def cv():
    return render_template(v['m.i.']['cv'])

@app.route('/more-info/cv/download')
def download_cv():
    filePath = v['m.i.']['cv-file']
    return send_file(filePath, as_attachment=True)

@app.route('/more-info/cv/view')
def view_cv():
    filePath = v['m.i.']['cv-file']  
    return send_file(filePath)


# solo ayuda dix template
@app.route('/ayuda-template')
def ayuda_template():
    data_links = [("ps-wt", 2, "¿Cómo crear una variable de entorno en Windows?")]
    return render_template(v['test'], data_links=data_links)


# Manejo del error 404
# @app.errorhandler(404)
# def page_not_found(error):
#     return render_template('404.html'), 404


if __name__ == '__main__':
   app.run(debug=True, port=8088, host='0.0.0.0')
