import os
import base64

__author__ = 'maruf'



def get_files(rootdir, exclude="local_settings.py"):
    file_list = []
    for root, subFolders, files in os.walk(rootdir):
        files = [ file for file in files if not file.endswith( ('.pyc','.tar') ) ]
        for filename in files:
            if filename == exclude:
                continue
            filePath = os.path.join(root, filename)
            file_list.append(filePath)

    return file_list


if __name__ == "__main__":
    path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../sampleprj"))
    print "Packaging application from [{0}]".format(path)
    file_list = get_files(path)
    root_len = len(path)
    file_data_list = []
    for filename in file_list:
        relative = filename[root_len:]
        print filename, " ", relative

        with open(filename, 'r') as content_file:
            content = content_file.read()
            file_data = {"name": relative, "data": content}
            file_data_list.append(file_data)

    sample_def_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sampleprojectdef.py")
    print sample_def_path

    with open(sample_def_path, 'w') as content_file:
        content_file.write("import base64\n\n")
        content_file.write("file_data_list=[\n")
        first = True
        for file_data in file_data_list:
            if not first:
                content_file.write(",\n")
            first = False
            content_file.write("{\n")
            name = file_data["name"]
            content_file.write("'name': '{0}', ".format(name))
            data = base64.b64encode(file_data["data"])
            content_file.write("'data': base64.b64decode('{0}')".format(data))
            content_file.write("\n}")

        content_file.write("]\n")
