# 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)

[((387, 402), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (392, 402), False, 'from flask import Flask\n'), ((647, 682), 'flask.send_from_directory', 'send_from_directory', (['"""static"""', 'path'], {}), "('static', path)\n", (666, 682), False, 'from flask import send_from_directory\n'), ((725, 754), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (740, 754), False, 'from flask import render_template\n'), ((813, 844), 'flask.request.args.get', 'request.args.get', (['"""title"""', 'None'], {}), "('title', None)\n", (829, 844), False, 'from flask import request\n'), ((968, 989), 'models.Location.selectbase', 'Location.selectbase', ([], {}), '()\n', (987, 989), False, 'from models import Location\n'), ((1132, 1175), 'math.ceil', 'ceil', (['(total_items / LOCATION_ITEMS_PER_PAGE)'], {}), '(total_items / LOCATION_ITEMS_PER_PAGE)\n', (1136, 1175), False, 'from math import ceil\n'), ((1828, 1859), 'flask.request.args.get', 'request.args.get', (['"""title"""', 'None'], {}), "('title', None)\n", (1844, 1859), False, 'from flask import request\n'), ((2160, 2180), 'flask.json.jsonify', 'json.jsonify', (['movies'], {}), '(movies)\n', (2172, 2180), False, 'from flask import json\n'), ((1898, 1914), 'flask.json.jsonify', 'json.jsonify', (['[]'], {}), '([])\n', (1910, 1914), False, 'from flask import json\n'), ((877, 904), 'flask.request.args.get', 'request.args.get', (['"""page"""', '(1)'], {}), "('page', 1)\n", (893, 904), False, 'from flask import request\n'), ((1929, 1960), 'models.Location.select', 'Location.select', (['Location.title'], {}), '(Location.title)\n', (1944, 1960), False, 'from models import Location\n')]