# -*- coding: utf-8 -*-
import os
import shutil


def load_resources(prefix):
    import __res

    for i in range(0, __res.count()):
        key = __res.key_by_index(i)
        if str(key).startswith(prefix):
            print("Loading {} at {}".format(key, key[len(prefix) + 1:]))
            yield key[len(prefix) + 1:], __res.find(key)


def load_and_write_resources(prefix):
    """
    This method loads all resources from __res and write it as files.
    Works only for Arcadia building.
    """
    try:
        output_folder = prefix.lstrip('/')
        if os.path.isdir(output_folder):
            #shutil.rmtree(output_folder)
            pass
        for resource_path_suffix, resource_data in load_resources(prefix):
            resource_path = os.path.join(output_folder, resource_path_suffix)
            resource_dir = os.path.dirname(resource_path)
            if not os.path.isdir(resource_dir):
                os.makedirs(resource_dir)
            with open(resource_path, 'w') as f:
                f.write(resource_data)
    except ImportError as e:
        raise Exception('Cannot import resources: {}'.format(e))
