import datetime
import inspect

from flask import Blueprint, current_app, make_response, render_template, request, send_from_directory, abort
from flask_login import login_required

import func
import database

TV_Movies = Blueprint("tv_movies", __name__, template_folder="templates")


@TV_Movies.route("/tv_movies")
@login_required
def index():
    try:
        page = request.args.get("page", 1, type=int)
        max_items = request.args.get("max_items", 30, type=int)
        tv = database.get_all_tv_movies()
        start = max_items * (page - 1)
        end = len(tv) if len(tv) < max_items * page else max_items * page
        tv_dict = []
        for tv_item in tv:
            item = tv_item[0].__dict__
            item.pop("_sa_instance_state", None)
            item.pop("path", None)
            tv_dict.append((item, tv_item[1]))
        return render_template(
            "tv_movies/index.html", title="tv & movies", tv_shows=tv_dict, page=page, max_items=max_items, start=start, end=end, item_count=len(tv)
        )
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@TV_Movies.route("/tv_movies/search")
@login_required
def search():
    try:
        page = request.args.get("page", 1, type=int)
        max_items = request.args.get("max_items", 30, type=int)
        start = 0
        end = 0
        query = request.args.get("q")
        tv = []
        if query:
            tv = database.db_search_tv_movie(query)
            start = max_items * (page - 1)
            end = len(tv) if len(tv) < max_items * page else max_items * page
        tv_dict = []
        for tv_item in tv:
            item = tv_item[0].__dict__
            item.pop("_sa_instance_state", None)
            item.pop("path", None)
            tv_dict.append((item, tv_item[1]))
        return render_template(
            "tv_movies/search.html", title="tv_movies", tv_shows=tv_dict, page=page, max_items=max_items, start=start, end=end, item_count=len(tv)
        )
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@TV_Movies.route("/tv_movies/<tmdb_id>", methods=["GET", "POST"])
@login_required
def tv_movie_viewer(tmdb_id):
    try:
        tv_movie = database.get_tv_movie_by_tmdb_id(tmdb_id)
        if type(tv_movie) is database.Movie:
            extended = request.args.get("extended", default=False, type=bool)
            directors_cut = request.args.get("directors_cut", default=False, type=bool)
            return movie_view(tmdb_id, extended=extended, directors_cut=directors_cut)
        else:
            return episode_viewer(tmdb_id)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@login_required
def movie_view(tmdb_id, extended=False, directors_cut=False):
    try:
        if request.method == "POST":
            time = int(request.args.get("time", type=float))
            length = int(request.args.get("length", type=float, default=0))
            finished = True if request.args.get("finished", default="false") == "true" else False
            database.update_user_tv_movie_data(tmdb_id, None, time, length, finished, extended, directors_cut)
            return make_response("", 201)
        else:
            movie_data = database.db_get_movie_by_tmdb_id(tmdb_id, extended=extended, directors_cut=directors_cut)
            user_data = database.db_get_user_tv_movie_data(movie_data.tmdb_id, extended=extended, directors_cut=directors_cut)
            chapters = func.get_chapters(movie_data.path)
            if not user_data:
                user_data = database.update_user_tv_movie_data(movie_data.tmdb_id, None, 0, 0)
            return render_template(
                "tv_movies/movieViewer.html", title="Movies: " + movie_data.title, movie=movie_data, user_data=user_data, chapters=chapters
            )
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@login_required
def episode_viewer(tmdb_id):
    try:
        if request.method == "POST":
            time = int(request.args.get("time", type=float))
            parent_id = request.args.get("parent", type=str)
            length = int(request.args.get("length", type=float, default=0))
            finished = True if request.args.get("finished", default="false") == "true" else False
            database.update_user_tv_movie_data(tmdb_id, parent_id, time, length, finished)
            return make_response("", 201)
        else:
            tv_show = database.get_tv_show(tmdb_id)
            episodes = database.get_tv_show_episodes_by_tmdb_id(tmdb_id)
            if len(episodes) == 0:
                abort(404)
            season_num = request.args.get("season", type=int, default=None)
            episode_num = request.args.get("episode", type=int, default=None)
            user_tv_show_data = database.db_get_user_tv_show_episodes_data(tmdb_id)
            if not season_num and not episode_num:
                (current_episode, user_data) = database.db_get_current_tv_show_episode_and_data(tmdb_id, episodes)
                season_num = current_episode.season
                episode_num = current_episode.episode
                chapters = func.get_chapters(current_episode.path)
                if not user_data:
                    user_data = database.update_user_tv_movie_data(current_episode.tmdb_id, tmdb_id, 0, 0)
            else:
                current_episode = episodes[0]
                user_data = database.UserTvMovieData(("", "", "", 0, 0, False, datetime.datetime.min, False, False))
                for episode in episodes:
                    if episode.season == season_num and episode.episode == episode_num:
                        current_episode = episode
                        user_data = database.db_get_user_tv_movie_data(current_episode.tmdb_id)
                        if not user_data:
                            user_data = database.update_user_tv_movie_data(current_episode.tmdb_id, tmdb_id, 0, 0)
                        break
                else:
                    for episode in episodes:
                        if episode.season == season_num:
                            current_episode = episode
                            episode_num = episode.episode
                            user_data = database.db_get_user_tv_movie_data(current_episode.tmdb_id)
                            if not user_data:
                                user_data = database.update_user_tv_movie_data(current_episode.tmdb_id, tmdb_id, 0, 0)
                            break
                chapters = func.get_chapters(current_episode.path)
            return render_template(
                "tv_movies/episodeViewer.html",
                title="Tv: " + tv_show.title,
                episodes=episodes,
                season_num=season_num,
                episode_num=episode_num,
                episode=current_episode,
                user_data=user_data,
                user_tv_show_data=user_tv_show_data,
                chapters=chapters,
            )
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@TV_Movies.route("/tv_movies/get_movie/<tmdb_id>")
@login_required
def get_movie(tmdb_id):
    extended = request.args.get("extended", default=False, type=bool)
    directors_cut = request.args.get("directors_cut", default=False, type=bool)
    res_4k = request.args.get("res_4k", default=False, type=bool)
    movie_data = database.db_get_movie_by_tmdb_id(tmdb_id, extended=extended, directors_cut=directors_cut)
    filename: str = movie_data.path
    if res_4k:
        filename = filename.replace(f"({movie_data.year})", f"({movie_data.year})(4K)")
    response = make_response(send_from_directory(func.MOVIES_DIRECTORY, filename))
    response.headers["content-type"] = "video/webm"
    return response


@TV_Movies.route("/tv_movies/get_episode/<tmdb_id>")
@login_required
def get_episode(tmdb_id):
    episode_data = database.db_get_episode_by_tmdb_id(tmdb_id)
    filename: str = episode_data.path
    response = make_response(send_from_directory(func.TV_SHOWS_DIRECTORY, filename))
    response.headers["content-type"] = "video/webm"
    return response
