from io import BytesIO
from pathlib import Path
from zipfile import ZipFile

FS_ROOT = '/srv/www/atr0phy.net/acks/quests'
URL_ROOT = 'https://atr0phy.net/acks/quests'
ASSET_EXTENSIONS = ('png', 'jpg', 'jpeg', 'dungeondraft_map', 'wonderdraft_map', 'wxx')

def load_quests():
    quest_list = {}

    fs = Path(FS_ROOT)
    for e in fs.iterdir():
        if not e.is_dir():
            continue

        # Each directory correlates to a level group
        quest_level_url_name = e.name.replace('Level', '').replace('-', '').replace(' ', '')

        # Gather quests under each level
        quest_list[quest_level_url_name] = load_quest_level_directory(e)
    return quest_list

def load_quest_level_directory(qdir):
    this_level = []
    for e in qdir.iterdir():
        if not e.is_dir():
            continue

        # Each directory is a quest for this level
        this_level.append(e.name)
    return this_level

def get_quest_details(level, quest_name):
    level_range = str(level)
    folder_name = "Level {0} - {1}".format(level_range[0], level_range[1])

    quest_path = "{}/{}/{}".format(FS_ROOT, folder_name, quest_name)
    fs = Path(quest_path)

    if not fs.exists() or not fs.is_dir():
        print('EXITING {}'.format(fs))
        return None

    quest = {}
    quest['name'] = fs.name
    quest['download'] = (level, quest_name)
    quest['assets'] = []

    def urlify(path):
        return {'display': path.name, 'url': path.as_posix().replace(FS_ROOT, URL_ROOT)}

    def read_coordinates(path):
        return path.read_text()

    for e in fs.iterdir():
        if e.name.endswith(ASSET_EXTENSIONS):
            quest['assets'].append(urlify(e))
        elif e.name == 'info.html':
            quest['info'] = urlify(e)
        elif e.name == 'tsv.txt':
            quest['tsv'] = urlify(e)
        elif e.name == 'coordinates.txt':
            quest['coords'] = read_coordinates(e)

    print("Quest: {}".format(quest))
    return quest

def get_quest_archive(level, quest_name):
    level_range = str(level)
    folder_name = "Level {0} - {1}".format(level_range[0], level_range[1])

    quest_path = "{}/{}/{}".format(FS_ROOT, folder_name, quest_name)
    fs = Path(quest_path)

    if not fs.exists() or not fs.is_dir():
        print('EXITING {}'.format(fs))
        return None

    file_path_list = []
    for e in fs.iterdir():
        file_path_list.append((e.as_posix(), e.name))

    archive_mem = BytesIO()
    with ZipFile(archive_mem, 'w') as archive:
        for f in file_path_list:
            archive.write(f[0], f[1])
    archive_mem.seek(0)

    return archive_mem
