#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from flask import Blueprint, g, redirect, render_template, request, url_for
from database import db_session
import json
from models.person import Person
from sqlalchemy.orm.exc import NoResultFound
import time
from werkzeug.local import LocalProxy

person_names_json = json.dumps([i[0] for i in db_session.query(Person.name.distinct())])

def register(app):

    # 루트
    @app.route('/person/', methods=['GET'])
    def person_main():
        query = request.args.get('q', None)
        if query is not None:
            return redirect(url_for('search', query=query))

        # TODO: 기본 페이지
        return render_template('layout.html')

    @app.route('/person/all-names.json', methods=['GET'])
    def person_all_names():
        return person_names_json

    # 이름으로 검색
    @app.route('/person/q/<query>', methods=['GET'])
    def search(query):
        # TODO: validation & sanitization
        # TODO: 처음엔 몇 개만 받아오고, '더 보기'를 누르면 나머지를 가져옴
        results = Person.query.filter(Person.name.like(u'%{0}%'.format(query))).all()

        if len(results) == 1:
            person = results[0]
            return redirect(url_for('person', id=person.id))

        return render_template('search-results.html', results=results,
                query=query)

    # 사람
    @app.route('/person/<int:id>', methods=['GET'])
    def person(id):
        try:
            person = Person.query.filter_by(id=id).one()
        except NoResultFound, e:
            return render_template('not-found.html'), 404

        try:
            person_extra_vars = json.loads(person.extra_vars)
            if type(person_extra_vars.get('experience', None)) in [str, unicode]:
                person_extra_vars['experience'] = [person_extra_vars['experience']]
        except ValueError, e:
            pass

        log_person(id)
        # XXX: script tag가 포함되어 있으면 pjax 불가
        return render_template('person.html', person=person,
                person_extra_vars=person_extra_vars, is_pjax=False)

def log_person(id):
    # FIXME: make this work w/ postgres
    # db['log_person'].insert({
    #     'id': id,
    #     'date': time.time()
    # })
    pass

@@ -42,16 +42,57 @@
 -8 -*-%0A%0A
+import json%0Aimport operator%0Aimport time%0A%0A
 from fla
@@ -104,19 +104,8 @@
 port
- Blueprint,
  g, 
@@ -157,79 +157,29 @@
 rom 
-database import db_session%0Aimport json%0Afrom models.person import Person
+sqlalchemy import or_
 %0Afro
@@ -220,28 +220,16 @@
 ltFound%0A
-import time%0A
 from wer
@@ -263,116 +263,149 @@
 xy%0A%0A
-person_names_json = json.dumps(%5Bi%5B0%5D for i in db_session.query(Person.name.distinct())%5D)%0A%0Adef register(app):
+from database import db_session%0Afrom models.person import Person%0A%0A%0Adef register(app):%0A%0A    person_names_json = json.dumps(all_person_names())
 %0A%0A  
@@ -1025,16 +1025,41 @@
 .filter(
+or_(%0A                    
 Person.n
@@ -1089,16 +1089,100 @@
 t(query)
+),%0A                    Person.name_en.ilike(u'%25%7B0%7D%25'.format(query))%0A                
 )).all()
@@ -2137,16 +2137,235 @@
 False)%0A%0A
+%0Adef all_person_names():%0A    name_tuples = %5Blist(i) for i in db_session.query(%0A        Person.name,%0A        Person.name_en,%0A        )%5D%0A    all_names = list(set(reduce(operator.add, name_tuples)))%0A    return all_names%0A%0A%0A
 def log_

Enable search by English name