from pyramid.view import view_config
from pyramid.httpexceptions import HTTPNotFound, HTTPFound
from docutils import core
import markdown
import datetime #<- will be used to set default dates on models

from ..models.entries import *
from webhelpers2.text import urlify #<- will generate slugs
from webhelpers2.date import distance_of_time_in_words #<- human friendly dates
from urllib.parse import urlparse


@view_config(route_name='blog', renderer='../templates/blog.jinja2')
def blog(request):
    # get post id from request
    blog_id = request.matchdict['id']
    entry = get_entries_by_id(request, blog_id)
    if not entry:
        request.session.flash(u"Page non trouvée : %s" % blog_id, 'warning')
        return HTTPFound(location=request.route_url('home'))

    if entry.language == 'vi':
        scr_label = 'Nguồn'
        rel_label = 'Nội dung liên quan'
    elif entry.language == 'en':
        scr_label = 'Source'
        rel_label = 'Related Items'
    else:
        scr_label = 'Source'
        rel_label = 'Contenu corrélé'

    # insèrer le path de static/img
    body = entry.body.replace('static/', "%s/static/" % request.application_url)
    # content type /= html ?
    if entry.content_type == "text/markdown":
        # convertir de markdown en HTML
        body_html = markdown.markdown(body, extensions=['footnotes'])
    elif entry.content_type == "text/x-rst":
        parts = core.publish_parts(
                          source=body,
                          writer_name='html')
        body_html = parts['body_pre_docinfo']+parts['fragment']
    else:
        body_html = body

    # lire le contenu correle
    # import pdb; pdb.set_trace()
    if entry.related != "0":
        related = get_entries_by_id(request, entry.related)
    else:
        related = None

    return {
        'page_title': entry.title,
        'entry': entry,
        'related': related,
        'scr_label': scr_label,
        'rel_label': rel_label,
        'body_html': body_html,
        }


@view_config(route_name='blog_copy', renderer='../templates/blog_copy.jinja2', permission='view')
def blog_copy(request):
    # get post parameters from request
    topic = request.matchdict['topic'] 
    blog_id = request.matchdict['id']

    # get the post
    entry = get_entries_by_id(request, blog_id)
    if not entry:
        request.session.flash("Page non trouvée : %s" % blog_id, 'warning')
        return HTTPFound(location=request.route_url('topic', topic=topic))

    # create a new post
    new_values = {}
    new_values['title'] = entry.title + ' - copie'
    new_values['body'] = entry.body
    new_values['created'] = datetime.datetime.now()
    new_values['edited'] = datetime.datetime.now()
    new_values['topic_id'] = topic
    new_values['tag'] = entry.tag
    new_values['author'] = entry.author
    new_values['status'] = 'brouillon'
    new_values['creator'] = request.authenticated_userid
    new_values['editor'] = ''
    update_entry(request, '0', new_values)
    return HTTPFound(location=request.route_url('topic', topic=topic))

    request.session.flash("La page a été duppliquée avec succès", 'success')
    return HTTPFound(location=request.route_url('topic', topic=topic))


@view_config(route_name='blog_edit', renderer='../templates/blog_edit.jinja2', permission='view')
def blog_edit(request):
    # get post parameters from request
    topic = request.matchdict['topic'] 
    blog_id = request.matchdict['id']
    url = request.route_url('blog_edit',topic=topic, id=blog_id)

    # get the list of tags of this topic
    tags = get_tags_byTopic(request, topic)

    if blog_id == '0':
        # create a new post
        entry = {}
        entry['title'] = ''
        entry['body'] = ''
        entry['created'] = datetime.datetime.now()
        entry['edited'] = datetime.datetime.now()
        entry['topic_id'] = topic
        entry['tag'] = ''
        entry['author'] = ''
        entry['source_link'] = ''
        entry['related'] = '0'
        entry['status'] = ''
        entry['creator'] = request.authenticated_userid
        entry['editor'] = ''
        entry['language'] = 'vi'
        entry['content_type'] = 'text/markdown'
        page_title = 'Nouvelle page'
        url_retour = request.route_url('topic', topic=topic)

    else:
        # modify post
        entry = get_entries_by_id(request, blog_id)
        if not entry:
            request.session.flash("Page non trouvée : %s" % blog_id, 'warning')
            return HTTPFound(url_retour)
        page_title = 'Modifier : ' + entry.title
        entry_slug = urlify(entry.title)
        url_retour = request.route_url('blog', id=blog_id, slug=entry_slug)

    if 'form.submitted' in request.params:
        new_values = {}
        for param in entry.keys():
            if param in request.params and request.params[param] != entry[param]:
                new_values[param] = request.params[param]
                if param == 'title':
                    # interdire le car '/' dans le titre à cause du slug
                    new_values['title'] = new_values['title'].replace('/','.')
                elif param == 'body':
                    new_values['body'] = new_values['body'].strip()
                elif param == 'source_link':
                    # controles du champ 'source_link'
                    src_link = new_values['source_link']
                    if src_link != '':
                        if src_link[:4] != 'http':
                            request.session.flash("Le lien dans Source est invalide !", 'danger')
                            return HTTPFound(location=url_retour)
                        # get the domain from 'source_link'
                        new_values['source_site'] = urlparse(src_link).netloc
                elif param == 'related':
                    # lire le contenu correle
                    if new_values['related'] != '0':
                        related = get_entries_by_id(request, new_values['related'])
                        if not related:
                            request.session.flash("Le contenu corrélé est invalide !", 'danger')
                            return HTTPFound(location=url_retour)
                    

        
        if new_values:            
            new_values['topic_id'] = topic
            new_values['editor'] = request.authenticated_userid
            new_values['edited'] = datetime.datetime.now()

            update_entry(request, blog_id, new_values)
            return HTTPFound(location=url_retour)

    if 'form.deleted' in request.params:
        delete_entry(request, blog_id)
        request.session.flash("La page a été supprimée avec succès.", 'success')
        return HTTPFound(location=request.route_url('topic', topic=topic))

    return {
        'page_title': page_title,
        'url': url,
        'url_retour': url_retour,
        'blog_id': blog_id,
        'entry': entry,
        'tags': tags,
        }


@view_config(route_name='blog_search', renderer='../templates/blog_search.jinja2')
def blog_search(request):

    criteria = ''

    items = []
    if 'form.submitted' in request.params:
        criteria = request.params['criteria']
        # si afficher tous les fiches ?
        items = get_entries_by_criteria(request, criteria)
        
    return {
        'page_title': "Rechercher",
        'items': items,
        'criteria': criteria,
    }

@view_config(route_name='section', renderer='../templates/section.jinja2')
def section(request):
    topic = request.matchdict['topic'] 
    tag = request.matchdict['tag'] 

    # get the tag record
    tag_record = get_tags_byTag(request, topic, tag)
    # convertir champ topic_quote en HTML
    # topic_quote = markdown.markdown(tag_record.topic_quote)
    # insèrer le path de static/img
    # topic_quote = topic_quote.replace('static/', "%s/static/" % request.application_url)


    # generate the items list group by tag
    liste = ''
    # lire toutes les docs du topic / tag
    items = get_entries_by_topic(request, topic, tag)
    if items:
        liste += '<div><table class="table table-sm table-borderless ms-4 mb-4"">'
        for item in items:
            item_slug = urlify(item.title)
            liste += '<tr>'
            liste += '<td width="%s"><a href="%s">%s</a></td>' % ('40%', request.route_url('blog', id=item.id, slug=item_slug), item.title)
            liste += '<td width="%s">%s</td>' % ('60%', item.description)
            if item.status != 'publié':
                liste += '<td><span class="label label-danger">%s</span></td>' % item.status
            liste += '</tr>'
        liste += '</tbody></table></div>'
    else:
        liste += '<ul><li> </li></ul>'
    return {
            'page_title': tag_record.tag_name,
            'topic': topic,
            'liste': liste,
        }

@view_config(route_name='topic', renderer='../templates/topic.jinja2')
def topic(request):
    topic = request.matchdict['topic'] 

    # get the topic record
    topic_record = get_topic_byTopic(request, topic)
    # convertir champ topic_quote en HTML
    topic_quote = markdown.markdown(topic_record.topic_quote)
    # insèrer le path de static/img
    topic_quote = topic_quote.replace('static/', "%s/static/" % request.application_url)

    # get all the tags of this topic
    tags = get_tags_byTopic(request, topic)

    # generate the items list group by tag
    liste = ''
    for tag in tags:
        liste += '<h3>' + tag.tag_name + '</h3>'
        # lire toutes les docs du topic
        items = get_entries_by_topic(request, topic, tag.tag)
        if items:
            liste += '<div><table class="table table-sm table-borderless ms-4 mb-4"">'
            liste += '<tbody class="table-group-divider">'
            for item in items:
                item_slug = urlify(item.title)
                liste += '<tr>'
                liste += '<td><a href="%s">%s</a></td>' % (request.route_url('blog', id=item.id, slug=item_slug), item.title)
                liste += '<td>%s</td>' % item.author
                liste += '<td>%s</td>' % item.create_date
                if item.status != 'publié':
                   liste += '<td><span class="label label-danger">%s</span></td>' % item.status
                liste += '</tr>'
            liste += '</tbody></table></div>'
        else:
            liste += '<ul><li> </li></ul>'
    return {
            'page_title': topic_record.topic_name,
            'topic': topic,
            'topic_quote': topic_quote,
            'liste': liste,
        }


@view_config(route_name='stats_pages', renderer='../templates/stats_pages.jinja2')
def stats_pages(request):

    entries = get_entries_count_by_topic(request)

    return {
        'page_title': "Statistiques par topics",
        'entries': entries,
        }
