from flask import Blueprint, request, render_template, redirect, url_for, \
    escape, make_response
from recipyGui import recipyGui
from .forms import SearchForm, AnnotateRunForm
from tinydb import TinyDB, Query, where
import re
from dateutil.parser import parse
import os
from ast import literal_eval
from json import dumps
from recipyCommon.tinydb_utils import listsearch


routes = Blueprint('routes', __name__, template_folder='templates')

if not os.path.exists(os.path.dirname(recipyGui.config.get('tinydb'))):
        os.mkdir(os.path.dirname(recipyGui.config.get('tinydb')))


@recipyGui.route('/')
def index():
    form = SearchForm()

    query = request.args.get('query', '').strip()

    db = TinyDB(recipyGui.config.get('tinydb'))

    if not query:
        runs = db.all()
    else:
        # Search run outputs using the query string
        runs = db.search(
            where('outputs').any(lambda x: listsearch(query, x)) |
            where('inputs').any(lambda x: listsearch(query, x)) |
            where('script').search(query) |
            where('notes').search(query) |
            where('unique_id').search(query))
    runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')) if x['date'] is not None else x['eid'], reverse=True)

    run_ids = []
    for run in runs:
        if 'notes' in run.keys():
            run['notes'] = str(escape(run['notes']))
        run_ids.append(run.eid)

    db.close()

    return render_template('list.html', runs=runs, query=query, form=form,
                           run_ids=str(run_ids),
                           dbfile=recipyGui.config.get('tinydb'))


@recipyGui.route('/run_details')
def run_details():
        form = SearchForm()
        annotateRunForm = AnnotateRunForm()
        query = request.args.get('query', '')
        run_id = int(request.args.get('id'))
        active_page = request.args.get('active_page', '')

        db = TinyDB(recipyGui.config.get('tinydb'))
        r = db.get(eid=run_id)
        diffs = db.table('filediffs').search(Query().run_id == run_id)

        db.close()

        return render_template('details.html', query=query, form=form,
                               annotateRunForm=annotateRunForm, run=r,
                               dbfile=recipyGui.config.get('tinydb'),
                               diffs=diffs, active_page=active_page)


@recipyGui.route('/latest_run')
def latest_run():
    db = TinyDB(recipyGui.config.get('tinydb'))

    runs = db.all()
    runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')), reverse=True)

    db.close()

    return redirect(url_for('run_details', query='', id=runs[0].eid,
                    active_page='latest_run'))

@recipyGui.route('/annotate', methods=['POST'])
def annotate():
    notes = request.form['notes']
    run_id = int(request.form['run_id'])

    query = request.args.get('query', '')

    db = TinyDB(recipyGui.config.get('tinydb'))
    db.update({'notes': notes}, eids=[run_id])
    db.close()

    return redirect(url_for('run_details', id=run_id, query=query))

@recipyGui.route('/runs2json', methods=['POST'])
def runs2json():
    run_ids = literal_eval(request.form['run_ids'])
    db = TinyDB(recipyGui.config.get('tinydb'))
    runs = [db.get(eid=run_id) for run_id in run_ids]
    db.close()

    response = make_response(dumps(runs, indent=2, sort_keys=True))
    response.headers['content-type'] = 'application/json'
    response.headers['Content-Disposition'] = 'attachment; filename=runs.json'
    return response

@@ -1689,28 +1689,24 @@
 _details():%0A
-    
     form = S
@@ -1713,28 +1713,24 @@
 earchForm()%0A
-    
     annotate
@@ -1761,20 +1761,16 @@
 m()%0A    
-  
-  
 query = 
@@ -1799,28 +1799,24 @@
 y', '')%0A    
-   
- 
 run_id = int
@@ -1836,28 +1836,24 @@
 .get('id'))%0A
-    
     active_p
@@ -1895,20 +1895,16 @@
 ', '')%0A%0A
-    
     db =
@@ -1943,20 +1943,16 @@
 nydb'))%0A
-    
     r = 
@@ -1970,28 +1970,24 @@
 run_id)%0A    
-  
-  
 diffs = db.t
@@ -2038,20 +2038,16 @@
 un_id)%0A%0A
-    
     db.c
@@ -2058,20 +2058,16 @@
 ()%0A%0A    
-   
- 
 return r
@@ -2113,36 +2113,32 @@
 ery, form=form,%0A
-    
                 
@@ -2207,36 +2207,32 @@
                 
-    
 dbfile=recipyGui
@@ -2253,16 +2253,29 @@
 inydb'),
+ diffs=diffs,
 %0A       
@@ -2297,25 +2297,8 @@
     
-     diffs=diffs,
  act

Fix indentation of run details view