import inspect
import json
import os

from flask import Blueprint, abort, current_app, jsonify, render_template, request, send_file
from flask_login import login_required

import database

Games = Blueprint("games", __name__, template_folder="templates")


@Games.route("/games")
@login_required
def index():
    try:
        page = request.args.get("page", 1, type=int)
        max_items = request.args.get("max_items", 30, type=int)
        games = database.get_all_games()
        start = max_items * (page - 1)
        end = len(games) if len(games) < max_items * page else max_items * page
        return render_template("games/index.html", title="Games", games=games)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/get_games")
@login_required
def get_games():
    try:
        games = database.get_all_games()
        games_json = {}
        for game in games:
            games_json[game.game_id] = {
                "id": game.game_id,
                "title": game.title,
                "description": game.description,
                "poster_path": game.poster_path,
                "windows": game.windows,
                "mac": game.mac,
                "linux": game.linux,
                "title_sanitized": game.title_sanitized,
            }
        return jsonify(games_json)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/get_games/windows")
@login_required
def get_games_windows():
    try:
        games = database.get_windows_games()
        games_json = {}
        for game in games:
            with open(os.path.join(game.path, "info.json")) as f:
                info = json.load(f)
            games_json[game.game_id] = {
                "id": game.game_id,
                "title": game.title,
                "description": game.description,
                "poster_path": game.poster_path,
                "windows": {"executable": info["windows"]["executable"]},
                "title_sanitized": game.title_sanitized,
            }
        return jsonify(games_json)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/get_games/mac")
@login_required
def get_games_mac():
    try:
        games = database.get_mac_games()
        games_json = {}
        for game in games:
            with open(os.path.join(game.path, "info.json")) as f:
                info = json.load(f)
            games_json[game.game_id] = {
                "id": game.game_id,
                "title": game.title,
                "description": game.description,
                "poster_path": game.poster_path,
                "title_sanitized": game.title_sanitized,
                "mac": {},
            }
            if "executable" in info["mac"].keys():
                games_json[game.game_id]["mac"] = {"executable": info["mac"]["executable"]}
        return jsonify(games_json)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/get_games/linux")
@login_required
def get_games_linux():
    try:
        games = database.get_linux_games()
        games_json = {}
        for game in games:
            with open(os.path.join(game.path, "info.json")) as f:
                info = json.load(f)
            games_json[game.game_id] = {
                "id": game.game_id,
                "title": game.title,
                "description": game.description,
                "poster_path": game.poster_path,
                "title_sanitized": game.title_sanitized,
                "linux": {"executable": info["linux"]["executable"]},
            }
        return jsonify(games_json)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/get_game/<int:game_id>")
@login_required
def get_game(game_id):
    try:
        game = database.get_game(game_id)
        if game:
            with open(os.path.join(game.path, "info.json")) as f:
                info = json.load(f)
            windows = None
            mac = None
            linux = None
            if "windows" in info.keys():
                windows = info["windows"]
            if "mac" in info.keys():
                mac = info["mac"]
            if "linux" in info.keys():
                linux = info["linux"]
            game_json = {
                "title": game.title,
                "game_id": game.game_id,
                "description": game.description,
                "poster_path": game.poster_path,
                "windows": windows,
                "mac": mac,
                "linux": linux,
                "title_sanitized": game.title_sanitized,
            }
            return jsonify(game_json)
        abort(404)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)


@Games.route("/games/download_hash/<int:game_id>/<file_hash>")
@login_required
def download_game_hash(game_id, file_hash):
    try:
        game = database.get_game(game_id)
        if game:
            folder = game.path
            path = os.path.join(folder, file_hash[:2], file_hash)
            return send_file(path, as_attachment=True, attachment_filename=file_hash)
        else:
            abort(404)
    except Exception as e:
        current_app.logger.error(inspect.stack()[0][3] + " " + str(type(e)) + " " + str(e))
        return str(type(e)) + " " + str(e)