import logging

import dateutil.parser

from flask import Blueprint, render_template, request, abort, redirect, url_for
from sqlalchemy.orm import joinedload

from . import db

from .db import session_scope

logger = logging.getLogger("quoted-forsooth.completion")

completion = Blueprint('completion', __name__)

@completion.route('/completion/')
def index():
    with session_scope() as session:
        cs = session.query(db.Completion).order_by(db.Completion.end_date).options(joinedload('source'))
        if 'type' in request.args:
            cs = cs.filter(db.Completion.source.has(db.Source.type == request.args.get('type')))
        return render_template('completion/index.html', completions=cs)

@completion.route('/completion/add/')
@completion.route('/completion/<int:completion_id>/edit/')
def edit(completion_id=None):
    with session_scope() as session:
        if completion_id:
            c = session.query(db.Completion).get(completion_id)
            if not c:
                abort(404)
        else:
            c = db.Completion()
        statuses = session.query(db.CompletionStatus).all()
        return render_template('completion/edit.html', completion=c, statuses=statuses)

@completion.route('/completion/add/', methods=['POST'])
@completion.route('/completion/<int:completion_id>/edit/', methods=['POST'])
def edit_post(completion_id=None):
    with session_scope() as session:
        notes = request.form['notes'].replace("\r\n", "\n")
        start_date = None
        if request.form.get('start_date'):
            start_date = dateutil.parser.parse(request.form['start_date'])
        end_date = None
        if request.form.get('end_date'):
            end_date = dateutil.parser.parse(request.form['end_date'])

        if not request.form.get('source'):
            abort(400)
        source = session.query(db.Source).get(int(request.form.get('source')))
        if not source:
            abort(400)

        if not request.form.get('status'):
            abort(400)
        status = session.query(db.CompletionStatus).get(int(request.form.get('status')))
        if status is None:
            abort(400)

        if 'db_id' in request.form:
            if completion_id and completion_id != request.form.get('db_id', type=int):
                raise ValueError("POSTed completion ID does not match URL.")
            completion = session.query(db.Completion).get(int(request.form['db_id']))
        else:
            completion = db.Completion()
            session.add(completion)

        completion.notes = notes
        completion.start_date = start_date
        completion.end_date = end_date
        completion.source = source
        completion.status = status

        session.commit()

        return redirect(source.internal_url)

@completion.route('/completion/<int:completion_id>/')
@completion.route('/completion/<int:completion_id>/<action>/')
def view(completion_id, action='view'):
    with session_scope() as session:
        c = session.query(db.Completion).get(completion_id)
        if not c:
            abort(404)
        if action == 'view':
            return render_template('completion/view.html', completion=c)
        else:
            abort(404)
