import io
import asyncio
from flask import jsonify, send_from_directory
from werkzeug.routing import PathConverter

from PandaCore import THUMB_DIR, app
from PandaCore.common import logger
from PandaCore.interfaces import archive, folder
from PandaCore.views import resources_blueprint
from PandaCore.utils import filepath, image
from PandaCore.threads import ScanThread


module_logger = logger.get_logger(__file__)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)


class EverythingConverter(PathConverter):
    regex = '.*?'


app.url_map.converters['everything'] = EverythingConverter


@resources_blueprint.route('/')
def debug():
    # ScanThread.queue.put(r'W:\H-Manga')
    # ScanThread.queue.put(r'W:\rar2')
    ScanThread.queue.put(r'C:\Users\Sean\Pictures\djs')
    return ""
    # test = archive.ArchiveInterface('~/test.zip')
    # return test.send_file('test2.png')


@resources_blueprint.route('/thumbs/<everything:path>//<path:file>')
def generate_thumb(path, file):
    path = filepath.normalize_path(path)
    if filepath.file_has_archive_extension(path):
        interface = archive.ArchiveInterface(path)
    else:
        interface = folder.FolderInterface(path)
    loop.run_until_complete(image.generate_thumbnail(file, interface))
    return send_from_directory(THUMB_DIR, interface.get_hash(file) + '.jpg')


