import os
from bottle import (get, post, redirect, request, route, run, static_file,
                    template)
import utils
import json

# Static Routes
@get("/js/<filepath:re:.*\.js>")
def js(filepath):
    return static_file(filepath, root="./js")


@get("/css/<filepath:re:.*\.css>")
def css(filepath):
    return static_file(filepath, root="./css")


@get("/images/<filepath:re:.*\.(jpg|png|gif|ico|svg)>")
def img(filepath):
    return static_file(filepath, root="./images")


@route('/')
def index():
    sectionTemplate = "./templates/home.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData={})


@route('/browse')
def browse():
    sectionTemplate = "./templates/browse.tpl"
    sectionData = utils.getShowsData()
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData=sectionData)


@route('/show/<show_id:int>')
def show(show_id):
    sectionData = utils.getShow(show_id)
    sectionTemplate = "./templates/show.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData=sectionData)


@route('/ajax/show/<show_id:int>')
def show(show_id):
    sectionData = utils.getShow(show_id)
    return template("./templates/show.tpl", result=sectionData)


@route('/show/<show_id:int>/episode/<episode_id:int>')
def episode(show_id, episode_id):
    sectionData = utils.findEpisode(show_id, episode_id)
    sectionTemplate = "./templates/episode.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData=sectionData)


@route('/ajax/show/<show_id:int>/episode/<episode_id:int>')
def episode(show_id, episode_id):
    sectionData = utils.findEpisode(show_id, episode_id)
    return template("./templates/episode.tpl", result=sectionData)


@route('/search')
def search():
    sectionTemplate = "./templates/search.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData={})

@post('/search')
def search():
    user_input = request.forms.get('q')
    sectionData = utils.searchResult(str(user_input))
    sectionTemplate = "./templates/search_result.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, query=user_input, sectionData={}, results=sectionData)


@route('/404')
def search():
    sectionTemplate = "./templates/404.tpl"
    return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData={})


run(host='localhost', port=os.environ.get(
    'PORT', 5000), debug=True, reloder=True)
