import os
from flask import jsonify, request, send_file
from PandaCore import models
from PandaCore.common import exceptions, logger
from PandaCore.models import Releases, Files, EntityMetadata, EntityTagMaps
from PandaCore.views import releases_blueprint
from PandaCore.utils import search, query, image
from PandaCore.interfaces import ReleaseInterface


module_logger = logger.get_logger(__file__)


@releases_blueprint.route('/')
def get_releases():
    return jsonify(query.get_all(Releases)[:10])


@releases_blueprint.route('/<int:db_id>')
def get_release(db_id: int):
    return jsonify(
        query.get_db_json(Releases, db_id, get_metadata=True))


@releases_blueprint.route('/<int:db_id>/thumb')
def get_thumb(db_id: int):
    return send_file(image.ensure_release_thumbnail(db_id))


# TODO: Implement stuff for archives
@releases_blueprint.route('/<int:db_id>/<int:file_index>')
def get_file(db_id: int, file_index: int):
    return jsonify(
        query.get_file_by_index(db_id, file_index, get_metadata=True))


@releases_blueprint.route('/<int:db_id>/<int:file_index>/image')
def open_file(db_id: int, file_index: int):
    file = query.get_file_by_index(db_id, file_index)
    interface = ReleaseInterface.get_interface(file['file_path'])
    return interface.send_file(file['file_name'])


@releases_blueprint.route('/<int:db_id>/files')
def get_files(db_id: int):
    return jsonify(query.get_release_files(db_id))


@releases_blueprint.route('/search/')
def search_for_releases():
    all_args = request.args.to_dict(flat=False)
    return jsonify(search.search(all_args, Releases))
