

from base import db, base_app, default_view, current_user, login_required, role_required
from base import call_view
from base.user import User
from modules.news import newsMod as news

# Local imports

from models import NewsPost, NewsPostComment

from flask import request, render_template, redirect, url_for, flash

# ##############################################################################
# Section: News Post Add/Edit/Comment
# ##############################################################################
@news.route('/view')
def default(error = None):
    posts = NewsPost.query.order_by('News_Post.pub_date DESC').all()
    return render_template('show_all_posts.html', posts=posts,error = error)



# ##############################################################################
# Name: view_post
# Synop: displays the post referenced by postid
@news.route('/view/<int:postid>', methods=['GET'])
def view_post(postid):
    post = NewsPost.query.get(postid)

    if post == None:
        return default_view()
    
    return render_template('show_post.html', post=post)


# ##############################################################################
# Name: add_post_comment
# Synop: add a new comment to the given post
@news.route('/view/<int:postid>', methods=['POST'])
@login_required
def add_post_comment(postid):
    post = NewsPost.query.get(postid)
    
    if post == None:
        return default_view("Invalid Request")

    pbody = request.form['comment-body']
    pauth = current_user.id
    
    if( pbody != None ):
        ncmt = NewsPostComment( post.id, pbody, pauth )
        db.session.add(ncmt)
        db.session.commit()
    
    return render_template('show_post.html', post=post)


# ##############################################################################
# Name: edit_post 
# Synop: deal with updates generated by edit_post_view
@news.route('/edit', methods=['POST'])
@login_required
def edit_post():

    pid = int(request.form['postid'])
    ptitle = str(request.form['posttitle'])
    pnbody = str(request.form['postbody'])
    
    newspost = NewsPost.query.get(pid)
    
    if(newspost == None):
        flash("Invalid Request", "Error")
        return default_view()
    
    if current_user.id != newspost.author:
        flash("Invalid User Premissions", "Error")
        return default_view()
    
    newspost.body  = pnbody
    newspost.title = ptitle
    
    db.session.commit()
    
    return default_view()

# ##############################################################################
# Name: edit_post_view
# Synop: the basic edit post view
@news.route('/edit/<int:postid>')
@login_required
def edit_post_view(postid):
    post = NewsPost.query.get(postid)
    if current_user.id != post.author:
        abort(401)
    
    npost = NewsPost('<input id="post-title" style="font-size: 24px; font-weight: bold; padding: 2px; width: 95%; height: 32px;" type=text name="posttitle" value="' + post.get_title() + '">',
                     '<textarea style="width:100%;" id="post-body-textbox" name="postbody">' + post.get_body() + '</textarea>',
                     current_user.id)
    
    return render_template('post_form.html', 
                           post_id=postid,
                           post=npost, 
                           form_action=url_for('.edit_post'),
                           form_name='editpost')

# ##############################################################################
# Name: add_post
# Synop: the basic add post view and handler
@news.route('/add', methods=['POST','GET'])
@role_required('admin')
def add_post():
    error = None;
    npost = NewsPost("<input id=\"post-title\" style=\"font-size: 24px; font-weight: bold; padding: 2px; width: 95%;height: 32px;\" type=text name=\"posttitle\" value=\"Post Title\">",
                    "<textarea style=\"width:100%;\" id=\"post-body-textbox\" name=\"postbody\">Post Body</textarea>",
                    current_user.id)
    if request.method == 'POST':
        
        ptitle  = request.form['posttitle']
        pbody   = request.form['postbody']
        
        if( ptitle != None and pbody != None ):
            
            npost.set_title(ptitle)
            npost.set_body(pbody)
            db.session.add(npost)
            db.session.commit()
            
            flash('New entry was successfully posted', 'Message')
            
            return redirect(url_for('.default'))

        flash("Invalid Request", "Error")
        return default_view()

    return render_template('post_form.html', 
                           post=npost, 
                           form_action=url_for('.add_post'),
                           form_name='addpost')

@news.route('/list')
@role_required('admin')
def admin_list_posts():
    return call_view('admin.list', model_name='NewsPost')

# ##############################################################################
# Name: delete_post
# Synop: delete the post specified by postid
@news.route('/del/<int:postid>')
@login_required
def delete_post(postid):
    pst = NewsPost.query.get(postid)
    
    if pst == None:
        flash("Invalid Request", "Error")
        return default_view();
    
    if current_user == pst.user:
        for comment in pst.comments:
            db.session.delete(comment)
        
        db.session.delete(pst)
        db.session.commit()
    else:
        flash("Insufficient Premissions", "Error")
        return default_view()
    return default_view()

