# coding: utf-8

'''フロントコントローラを提供する
'''

from math import ceil
import os

from flask import json
from flask import Flask
from flask import request
from flask import send_from_directory
from flask import render_template

# from json_loader import load_locations
# from json_loader import prepare_locations
from models import Location


# ページ毎のロケ地表示する
LOCATION_ITEMS_PER_PAGE = 20


app = Flask(__name__)
app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY']
app.config['ROOT'] = (app.config['APPLICATION_ROOT']
                      if app.config['APPLICATION_ROOT'] else '')


@app.route('/static/<path:path>')
def send_js(path):
    return send_from_directory('static', path)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/location')
def location():
    req_title = request.args.get('title', None)
    try:
        req_page = int(request.args.get('page', 1))
    except ValueError as e:
        req_page = 1

    query = Location.selectbase()

    if req_title:
        query = query.where(Location.title ** '%{}%'.format(req_title))

    total_items = query.count()
    total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE)

    current_page = req_page if req_page <= total_pages else total_pages

    query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE)

    locations = [l.as_dict() for l in query]

    return json.jsonify({
        'meta': {
            'pager_data': {
                'totalItems':  total_items,
                'totalPages':  total_pages,
                'currentItems': len(locations),
                'currentPage':  current_page,
                'itemsPerPage': LOCATION_ITEMS_PER_PAGE,
            },
        },
        'entities': {
            'locations': locations,
        },
    })


@app.route('/movie')
def movie():
    req_title = request.args.get('title', None)

    if not req_title:
        return json.jsonify([])

    query = (Location.select(Location.title)
                     .distinct()
                     .where(Location.title ** '%{}%'.format(req_title)))

    movies = [{'id': index, 'title': l.title} for index, l in enumerate(query)]

    return json.jsonify(movies)

[((24, 6, 24, 21), 'flask.Flask', 'Flask', ({(24, 12, 24, 20): '__name__'}, {}), '(__name__)', False, 'from flask import Flask\n'), ((32, 11, 32, 46), 'flask.send_from_directory', 'send_from_directory', ({(32, 31, 32, 39): '"""static"""', (32, 41, 32, 45): 'path'}, {}), "('static', path)", False, 'from flask import send_from_directory\n'), ((37, 11, 37, 40), 'flask.render_template', 'render_template', ({(37, 27, 37, 39): '"""index.html"""'}, {}), "('index.html')", False, 'from flask import render_template\n'), ((42, 16, 42, 47), 'flask.request.args.get', 'request.args.get', ({(42, 33, 42, 40): '"""title"""', (42, 42, 42, 46): 'None'}, {}), "('title', None)", False, 'from flask import request\n'), ((48, 12, 48, 33), 'models.Location.selectbase', 'Location.selectbase', ({}, {}), '()', False, 'from models import Location\n'), ((54, 18, 54, 61), 'math.ceil', 'ceil', ({(54, 23, 54, 60): 'total_items / LOCATION_ITEMS_PER_PAGE'}, {}), '(total_items / LOCATION_ITEMS_PER_PAGE)', False, 'from math import ceil\n'), ((80, 16, 80, 47), 'flask.request.args.get', 'request.args.get', ({(80, 33, 80, 40): '"""title"""', (80, 42, 80, 46): 'None'}, {}), "('title', None)", False, 'from flask import request\n'), ((91, 11, 91, 31), 'flask.json.jsonify', 'json.jsonify', ({(91, 24, 91, 30): 'movies'}, {}), '(movies)', False, 'from flask import json\n'), ((83, 15, 83, 31), 'flask.json.jsonify', 'json.jsonify', ({(83, 28, 83, 30): '[]'}, {}), '([])', False, 'from flask import json\n'), ((44, 23, 44, 50), 'flask.request.args.get', 'request.args.get', ({(44, 40, 44, 46): '"""page"""', (44, 48, 44, 49): '1'}, {}), "('page', 1)", False, 'from flask import request\n'), ((85, 13, 85, 44), 'models.Location.select', 'Location.select', ({(85, 29, 85, 43): 'Location.title'}, {}), '(Location.title)', False, 'from models import Location\n')]