# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
from sqlalchemy import exc
from app.home import blueprint
from flask import current_app,render_template, redirect, url_for, request,flash
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound

from datetime import datetime,timedelta
from app.base.models import *
from app.home.ws_forms import CreateWsForm, CreateWsNodeForm,ShareWs,BidForm,BidCommentForm

@blueprint.route('/index')
@login_required
def index():

    return render_template('index.html', segment='index')

# @blueprint.route('/<template>')
# @login_required
# def route_template(template):

#     try:

#         if not template.endswith( '.html' ):
#             template += '.html'

#         # Detect the current page
#         segment = get_segment( request )

#         # Serve the file (if exists) from app/templates/FILE.html
#         return render_template( template, segment=segment )

#     except TemplateNotFound:
#         return render_template('page-404.html'), 404
    
#     except:
#         return render_template('page-500.html'), 500

# # Helper - Extract current page name from request 
# def get_segment( request ): 

#     try:

#         segment = request.path.split('/')[-1]

#         if segment == '':
#             segment = 'index'

#         return segment    

#     except:
#         return None  

@blueprint.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()

@blueprint.route("/books/")
# @cache.cached(300)
def display_books():
    books = [book for book in Book.query.all()]
    current_app.logger.info("Displaying all books.")

    return render_template("books.htm", books=books)

@blueprint.route("/authors/")
# @cache.cached(300)
def display_authors():
    authors = [author for author in Author.query.all()]
    current_app.logger.info("Displaying all authors.")

    return render_template("authors.htm", authors=authors)

@blueprint.route("/ws/")
@login_required
# @cache.cached(300)
def show_ws():
    # ws = [ws for ws in Group.query.all()]
    ws = Group.get_ws_by_user(current_user.id)
    current_app.logger.info("get ws for users." +str(ws))

    return render_template("ws.htm", ws=ws, segment='index')

@blueprint.route("/ws/nodes/", methods=['GET'])
# @cache.cached(300)
@login_required
def show_ws_nodes():
    ws_id = request.args.get('ws_id')
    # ws = [ws for ws in Group.query.all()]
    ws_pst = Node.get_nodes_by_user(current_user.id, ws_id)
    current_app.logger.info("get nodes_post for users."+ str(ws_pst))

    return render_template("ws_nodes.htm", ws=ws_pst,ws_id=ws_id, segment='index')

@blueprint.route("/ws/nodes/bids")
# @cache.cached(300)
@login_required
def show_ws_nodes_bids():
    post_id = request.args.get('post_id')
    # ws = [ws for ws in Group.query.all()]
    res_node_bid = (
        db.session.query(Node).join(Node.accessed_by).join(Group.members).filter(User.id == 1).filter(Node.id ==post_id).all()
    )

    ws = Node.get_comments(post_id)
    current_app.logger.info("ws for users.")

    return render_template("ws_nodes_bids.htm", ws=ws,ws0=ws[0],ws1=ws[1],ws2=ws[2],post_id=post_id,postn=res_node_bid, segment='index')

@blueprint.route("/ws/create", methods=["GET", "POST"])
# @roles_required("admin")
def create_ws():
    form = CreateWsForm(request.form)
    if request.method == "POST" and form.validate():
        my_user = User.query.filter_by(id=current_user.id).first()
        frm_ws_name = form.ws_name.data
        current_app.logger.info("Adding a new author %s.", (frm_ws_name))
        add_ws = Group(
            ws_name=frm_ws_name,
            owner_id=current_user.id,
            members =[my_user]
            )
        try:
            db.session.add(add_ws)
            db.session.commit()
            # cache.clear()
            flash("Author successfully created.")
        except exc.SQLAlchemyError as e:
            flash("Author was not created.")
            current_app.logger.error(e)

            return redirect(url_for("home_blueprint.create_ws"))

        return redirect(url_for("home_blueprint.show_ws"))

    return render_template("create_ws.htm", form=form, segment='index')

@blueprint.route("/ws/nodes/create", methods=["GET", "POST"])
# @roles_required("admin")
@login_required
def create_ws_node():
    ws_id = request.args.get('ws_id')
    form = CreateWsNodeForm(request.form)
    if request.method == "POST" and form.validate():
        # my_user = User.query.filter_by(id=1).first()
        # my_grp = Group.query.filter_by(group_id=form.nd_ws_id.data).first()

        frm_nd_title = form.nd_title.data
        frm_nd_desc = form.nd_desc.data
        frm_nd_amount = form.nd_amount.data
        frm_nd_ws_id = form.nd_ws_id.data

        my_grp = Group.query.filter_by(group_id=frm_nd_ws_id).first()

        current_app.logger.info("Adding a new node %s.", (form))
        add_ws_node = Node(
            post_name=frm_nd_title,
            post_desc=frm_nd_desc,
            post_budget=frm_nd_amount,
            owner_id=current_user.id,
            accessed_by =[my_grp]
            )
        print(add_ws_node)
        try:
            db.session.add(add_ws_node)
            db.session.commit()
            # cache.clear()
            flash("Node was  successfully created.")
        except exc.SQLAlchemyError as e:
            flash("Author was not created.")
            current_app.logger.error(e)
            print(e)

            return redirect(url_for("home_blueprint.create_ws_node",ws_id=ws_id))

        return redirect(url_for("home_blueprint.show_ws_nodes",ws_id=frm_nd_ws_id))

    return render_template("create_ws_node.htm", form=form,ws_id=ws_id, segment='index')

@blueprint.route("/ws/share", methods=["GET", "POST"])
# @roles_required("admin")
@login_required
def share_ws():
    ws_id = request.args.get('ws_id')
    form = ShareWs(request.form)
    if request.method == "POST" and form.validate():
        frm_usr_name = form.usr_name.data
        # my_user = User.query.filter_by(id=current_user.id).first()
        my_user = User.query.filter_by(username=frm_usr_name).first()
        my_grp = Group.query.filter_by(group_id=form.nd_ws_id.data).first()

        # add_ws = Group(
        #     # ws_name=frm_ws_name,
        #     owner_id=current_user.id,
        #     members =[my_user]
        #     )
        my_grp.members.append(my_user)
        try:
            db.session.add(my_grp)
            db.session.commit()
            # cache.clear()
            flash("Author successfully created.")
        except exc.SQLAlchemyError as e:
            flash("Author was not created.")
            current_app.logger.error(e)

            return redirect(url_for("home_blueprint.create_ws"))

        return redirect(url_for("home_blueprint.show_ws"))

    return render_template("share_ws.htm", form=form,ws_id=ws_id, segment='index')

@blueprint.route("/ws/nodes/bids/create", methods=["GET", "POST"])
# @roles_required("admin")
@login_required
def create_ws_node_bids():
    ws_id = request.args.get('ws_id')
    post_id = request.args.get('post_id')
    form = BidForm(request.form)
    if request.method == "POST" and form.validate():
        my_user = User.query.filter_by(id=current_user.id).first()

        bid_cmt = Comment(

            message="$$$ "+form.bid_note.data, 
            owner_id=current_user.id,
            post_id=form.bid_post_id.data
            )
        bid = Bid(
            bid_amount=form.bid_amount.data, 
            bid_note=form.bid_note.data, 
            owner_id=current_user.id,
            post_id=form.bid_post_id.data
            )
        try:
            db.session.add(bid)
            db.session.add(bid_cmt)
            db.session.commit()
            # cache.clear()
            flash("Bid successfully created.")
        except exc.SQLAlchemyError as e:
            flash("Bid was not created.")
            current_app.logger.error(e)

            return redirect(url_for("home_blueprint.show_ws_nodes",post_id=post_id))

        return redirect(url_for("home_blueprint.show_ws_nodes_bids",post_id=form.bid_post_id.data))

    return render_template("create_bid.htm", form=form,ws_id=ws_id,post_id=post_id, segment='index')