# -*- coding: utf8 -*-
from .default import (
    execute_query,
)

def get_entries_by_topic(request, topic, tag):
    query = "SELECT *, strftime('%d/%m/%Y', created) AS create_date FROM entries WHERE topic_id = '{0}'".format(topic)
    if request.authenticated_userid == None:
        # if user is anonym, display only published posts
       query = query + " AND status='publié'"
    else:
        if request.authenticated_userid != 'admin':
            # if user is not 'admin', hide admin posts
            query =  query + " AND tag != '_admin'"
    if tag != '':
        query = query + " AND tag = '{0}'".format(tag)
        
    query = query + " ORDER BY tag, title;"
    results = request.dbsession.execute(query).fetchall()
    return results

def get_entries_by_criteria(request, criteria):
    search = "%{}%".format(criteria)
    query = f"SELECT *, strftime('%d/%m/%Y', edited) AS edit_date FROM entries WHERE title like '{search}' or body like '{search}'"
    if request.authenticated_userid == None:
        # if user is anonym, display only published posts
       query = query + " AND status='publié'"
    else:
        if request.authenticated_userid != 'admin':
            # if user is not 'admin', hide admin posts
            query =  query + " AND tag != '_admin'"
    query = query + " ORDER BY title;"
    results = request.dbsession.execute(query).fetchall()
    return results

def get_entries_by_id(request, id):
    # is id a numeber or a string ?
    # import pdb;pdb.set_trace()
    if id.isnumeric():
        query = """SELECT *, strftime('%d/%m/%Y', created) AS create_date,
                strftime('%d/%m/%Y', edited) AS edit_date FROM entries WHERE id=:id;"""
    else:
        query = """SELECT *, strftime('%d/%m/%Y', created) AS create_date,
                strftime('%d/%m/%Y', edited) AS edit_date FROM entries WHERE url_id=:id;"""
    results = request.dbsession.execute(query, {'id':id}).first()
    return results

def get_entries_count_by_topic(request):
    query = """SELECT topics.topic_name, tags.tag_name, count(entries.id) as count, strftime('%d/%m/%Y', created) AS create_date
    FROM entries 
    INNER JOIN topics ON entries.topic_id = topics.topic
    INNER JOIN tags ON entries.tag = tags.tag
    GROUP BY entries.tag ORDER BY entries.topic_id, entries.tag;"""
    results = request.dbsession.execute(query,).fetchall()
    return results


def get_last_edited(request):
    # gest the last edited posts
    query = "SELECT strftime('%d/%m/%Y', edited) AS edit_date, id, title, author, status FROM entries WHERE topic_id <> '_admin'"
    if request.authenticated_userid == None:
        # if user is anonym, display only published posts
       query = query + " AND status='publié'"

    query = query + " ORDER BY edited DESC LIMIT 10;"
    results = request.dbsession.execute(query).fetchall()
    return results

def get_activities(request):
    # gest the Activities section
    query = "SELECT * FROM entries WHERE topic_id = '_admin' AND title like 'Activities - column%' ORDER BY title;"
    results = request.dbsession.execute(query,).all()
    return results

def get_tags_byTag(request, topic, tag):
    # get tags 
    query = "SELECT * FROM tags WHERE topic=:topic and tag=:tag;"
    results = request.dbsession.execute(query, {'topic':topic, 'tag':tag}).first()
    return results

def get_tags_byTopic(request, topic):
    # get tags 
    query = "SELECT * FROM tags WHERE topic=:topic ORDER BY tag;"
    results = request.dbsession.execute(query, {'topic':topic}).all()
    return results

def get_tags_byId(request, id):
    query = "SELECT * FROM tags WHERE id=:id;"
    results = request.dbsession.execute(query, {'id':id}).first()
    return results

def get_topic_byTopic(request, id):
    # get the name of a given topic
    query = "SELECT * FROM topics WHERE topic=:topic;"
    results = request.dbsession.execute(query, {'topic':id}).first()
    return results

def get_topics(request):
    # get all topics
    query = "SELECT * FROM topics ORDER BY topic_name;"
    results = request.dbsession.execute(query, {'topic':id}).all()
    return results

def delete_entry(request, id):
    query = "DELETE FROM entries WHERE id = :id ;"
    execute_query(request, query, {'id': id})

def delete_tag(request, id):
    query = "DELETE FROM tags WHERE id = :id ;"
    execute_query(request, query, {'id': id})

def delete_topic(request, topic):
    query = "DELETE FROM topics WHERE topic = :topic ;"
    execute_query(request, query, {'topic': topic})

def update_entry(request, blog_id, new_values):
    # formater les champs
    s = ''
    for param in new_values.keys():
        if s:
            s += ",%s=:%s" % (param, param)
        else:
            s = "%s=:%s" % (param, param)

    # import pdb;pdb.set_trace()
    if blog_id == '0':
        query = """INSERT INTO entries (title, body, created, edited, topic_id, tag, author, status, creator, editor)
            VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{8}')""".format(
            new_values['title'].replace("'","''"), new_values['body'].replace("'","''"), new_values['created'], new_values['created'],
            new_values['topic_id'], new_values['tag'], new_values['author'], new_values['status'],
            new_values['editor'], new_values['editor'],)
    else:
        new_values['id'] = blog_id
        query = "UPDATE entries SET %s WHERE id = :id;" % s
    execute_query(request, query, new_values)

def update_tag(request, id, new_values):
    # formater les champs
    s = ''
    for param in new_values.keys():
        if s:
            s += ",%s=:%s" % (param, param)
        else:
            s = "%s=:%s" % (param, param)

    if id == '0':
        query = "INSERT INTO tags (topic, tag, tag_name) VALUES ('{0}', '{1}', '{2}')".format(
                new_values['topic'], new_values['tag'], new_values['tag_name'])
    else:
        new_values['id'] = id
        query = "UPDATE tags SET %s WHERE id = :id;" % s
    execute_query(request, query, new_values)

def update_topic(request, topic, new_values):
    # formater les champs
    s = ''
    for param in new_values.keys():
        if s:
            s += ",%s=:%s" % (param, param)
        else:
            s = "%s=:%s" % (param, param)
    if topic == '0':
        query = "INSERT INTO topics (topic, topic_name, topic_language, topic_quote) VALUES ('{0}', '{1}', '{2}', '{3}')".format(
                topic, new_values['topic_name'], new_values['topic_language'], new_values['topic_quote'].replace("'","''"))
    else:
        new_values['topic'] = topic
        query = "UPDATE topics SET %s WHERE topic = :topic;" % s
    execute_query(request, query, new_values)
