from flask import Flask, request, render_template, make_response
from markupsafe import escape

from pathlib import Path
import sqlite3

con = sqlite3.connect("movies/movies.db")
cur = con.cursor()

app = Flask(__name__)

@app.route("/")
def hello_world():
    return '<p>Hello, go to the <a href="/movie/">movie list</a>!</p>'


@app.route('/movie/')
def movielist():
    return render_template('movielist.html', list=build_list())


@app.route('/movie/<int:id>')
def single_movie(id):
    id = escape(id)
    info = get_movie_info(id)
    return render_template('movie.html', **info)


@app.route('/actor/<int:id>')
def single_actor(id):
    id = escape(id)
    info = get_actor_info(id)
    return render_template('actor.html', **info)


@app.route('/api/moviecount/<int:actorid>')
def movie_count(actorid):
    res = cur.execute("SELECT count(DISTINCT movie_id) FROM actors WHERE actor_id=?", (actorid,))
    result, = res.fetchone()
    return {'count':result}


def build_list():
    res = cur.execute("SELECT year, title, id FROM movies")
    movie_list = res.fetchall()
    return movie_list



def get_movie_info(id):
    res = cur.execute("SELECT year, title FROM movies where id=?",(id,))
    movie = res.fetchone()
    if movie is None:
        return {}
    year, title = movie

    query = """\
     SELECT character,actor_id,name
     FROM actors as a JOIN people as p ON a.actor_id = p.id
     WHERE a.movie_id=?
     """

    stars = cur.execute(query, (id,))
    stars = stars.fetchall()

    info = {'name':title, 'year':year, 'actors':stars}

    return info    


def get_actor_info(id):
    res = cur.execute("SELECT name FROM people where id=?",(id,))
    actor = res.fetchone()
    if actor is None:
        return {}
    name, = actor

    query = """\
     SELECT m.id, title, year
     FROM movies as m JOIN actors as a ON a.movie_id = m.id
     WHERE a.actor_id=?
     ORDER BY YEAR ASC
     """

    movies = cur.execute(query, (id,))
    movies = movies.fetchall()

    info = {'name':name, 'movies':movies}

    return info    

