from datetime import datetime

from flask import Blueprint, request, render_template, redirect

from libertywiki.db import session
from libertywiki.decorators import check_access
from libertywiki.models import Page
from libertywiki.utils import AccessType

wiki = Blueprint('wiki', __name__, url_prefix='')


@wiki.route('/', defaults={'path': 'Main_Page'}, methods=['GET'])
@wiki.route('/<path:path>', methods=['GET'])
@check_access(AccessType.READ)
def index(path=None):
    page = Page.query.filter_by(slug=path).first()
    if not page:
        return redirect('/{}/edit'.format(path))
    return render_template('page.html', page=page)


@wiki.route('/<path:path>/edit', methods=['GET'])
@check_access(AccessType.WRITE)
def edit(path):
    page = Page.query.filter_by(slug=path).first()
    if not page:
        page = Page(title=path.replace('_', ' '))
    return render_template('edit.html', page=page)


@wiki.route("/<path:path>/edit", methods=['POST'])
@check_access(AccessType.WRITE)
def save(path):
    page = Page.query.filter_by(slug=path).first()
    if not page:
        page = Page()
    page.title = request.form.get('page-title')
    page.body = request.form.get('page-body')
    page.slug = page.title.replace(' ', '_')
    page.modified = datetime.now()
    session.add(page)
    session.commit()
    return redirect('/{}'.format(page.slug))
