import os
from enum import Enum
from ricecooker.classes import nodes, questions, files
from ricecooker.exceptions import UnknownContentKindError, UnknownFileTypeError, UnknownQuestionTypeError, raise_for_invalid_channel
from le_utils.constants import content_kinds,file_formats, format_presets, licenses, exercises, languages
from pressurecooker.encodings import get_base64_encoding

class FileTypes(Enum):
    """ Enum containing all file types Ricecooker can have

        Steps:
            AUDIO_FILE: mp3 files
            THUMBNAIL: png, jpg, or jpeg files
            DOCUMENT_FILE: pdf files
    """
    AUDIO_FILE = 0
    THUMBNAIL = 1
    DOCUMENT_FILE = 2
    VIDEO_FILE = 3
    YOUTUBE_VIDEO_FILE = 4
    VECTORIZED_VIDEO_FILE = 5
    VIDEO_THUMBNAIL = 6
    YOUTUBE_VIDEO_THUMBNAIL_FILE = 7
    HTML_ZIP_FILE = 8
    SUBTITLE_FILE = 9
    TILED_THUMBNAIL_FILE = 10
    UNIVERSAL_SUBS_SUBTITLE_FILE = 11
    BASE64_FILE = 12


FILE_TYPE_MAPPING = {
    content_kinds.AUDIO : {
        file_formats.MP3 : FileTypes.AUDIO_FILE,
        file_formats.PNG : FileTypes.THUMBNAIL,
        file_formats.JPG : FileTypes.THUMBNAIL,
        file_formats.JPEG : FileTypes.THUMBNAIL,
    },
    content_kinds.DOCUMENT : {
        file_formats.PDF : FileTypes.DOCUMENT_FILE,
        file_formats.PNG : FileTypes.THUMBNAIL,
        file_formats.JPG : FileTypes.THUMBNAIL,
        file_formats.JPEG : FileTypes.THUMBNAIL,
    },
    content_kinds.HTML5 : {
        file_formats.HTML5 : FileTypes.HTML_ZIP_FILE,
        file_formats.PNG : FileTypes.THUMBNAIL,
        file_formats.JPG : FileTypes.THUMBNAIL,
        file_formats.JPEG : FileTypes.THUMBNAIL,
    },
    content_kinds.VIDEO : {
        file_formats.MP4 : FileTypes.VIDEO_FILE,
        file_formats.VTT : FileTypes.SUBTITLE_FILE,
        file_formats.PNG : FileTypes.THUMBNAIL,
        file_formats.JPG : FileTypes.THUMBNAIL,
        file_formats.JPEG : FileTypes.THUMBNAIL,
    },
    content_kinds.EXERCISE : {
        file_formats.PNG : FileTypes.THUMBNAIL,
        file_formats.JPG : FileTypes.THUMBNAIL,
        file_formats.JPEG : FileTypes.THUMBNAIL,
    },
}



def guess_file_type(filepath, kind):
    """ guess_file_class: determines what file the content is
        Args:
            filepath (str): filepath of file to check
        Returns: string indicating file's class
    """
    if get_base64_encoding(filepath):
        return FileTypes.BASE64_FILE
    ext = os.path.splitext(filepath)[1][1:].lower()
    if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:
        return FILE_TYPE_MAPPING[kind][ext]
    return None


SAMPLE_PERSEUS = '{"answerArea":{"chi2Table":false,"periodicTable":false,"tTable":false,"zTable":false,"calculator":false},' + \
'"hints":[{"widgets":{},"images":{"web+graphie:C:/users/jordan/contentcuration-dump/0a0c0f1a1a40226d8d227a07dd143f8c08a4b8a5": {}},"content":"Hint #1","replace":false},{"widgets":{},"images":{},"content":"Hint #2","replace":false}],' +\
'"question":{"widgets":{"radio 1":{"type":"radio","alignment":"default","graded":true,"static":false,' +\
'"options":{"deselectEnabled":false,"multipleSelect":false,"choices":[{"correct":true,"content":"Yes"},{"correct":false,"content":"No"}],' +\
'"displayCount":null,"hasNoneOfTheAbove":false,"randomize":false,"onePerLine":true},"version":{"minor":0,"major":1}}},"images":{"web+graphie:C:/users/jordan/contentcuration-dump/0a0c0f1a1a40226d8d227a07dd143f8c08a4b8a5": {}},' +\
'"content":"Do you like rice?\\\"\\n\\n![](web+graphie:C:/users/jordan/contentcuration-dump/0a0c0f1a1a40226d8d227a07dd143f8c08a4b8a5)\\n\\n[[\\u2603 radio 1]]"},"itemDataVersion":{"minor":1,"major":0}}'

SAMPLE_TREE = [
    {
        "title": "TEST COMPRESSION",
        "id": "6cafe7",
        "author": "Revision 3",
        "description": "Become a master rice cooker",
        "license": licenses.CC_BY_NC_SA,
        "files": [
            {
                "path": "C:/users/jordan/contentcuration-dump/high resolution.mp4",
                # "ffmpeg_settings": {"max_width": 480, "crf": 20},
            },
            # {
            #     "path": "C:/users/jordan/Videos/testfolder/captions.vtt",
            #     "language": languages.getlang('en').code,
            # }
            # ,
            # {
            #     "path": "file:///C:/users/jordan/Videos/testfolder/captions.vtt",
            #     "language": languages.getlang('es').code,
            # }
        ],
    },
    {
        "title": "Rice 101",
        "id": "abd115",
        "description": "Learn about how rice",
        "children": [
            {
                "title": "Rice Distribution",
                "id": "aaaa4d",
                "files": [
                    {
                        "path" : "https://ia801407.us.archive.org/21/items/ah_Rice/Rice.mp3",
                    },
                    {
                        "path" : "https://upload.wikimedia.org/wikipedia/commons/b/ba/Rice_grains_(IRRI).jpg",
                    },
                ],
                "description": "Get online updates regarding world's leading long grain rice distributors, broken rice distributors, rice suppliers, parboiled rice exporter on our online B2B marketplace TradeBanq.",
                "license": licenses.PUBLIC_DOMAIN,
            },
            {
                "title": "Rice History",
                "id": "6ef99c",
                "description": "Discover the history of rice",
                "children": [
                    {
                        "title": "The History of Japanese Rice",
                        "id": "418799",
                        "author": "Sandra Lopez-Richter",
                        "license": licenses.CC_BY_NC_SA,
                        "files":[
                            {
                                "path" : "https://ia601301.us.archive.org/31/items/The_History_of_Japanese_Rice_Lopez-Richter/The_History_of_Japanese_Rice_Lopez-Richter.pdf",
                            },
                            {
                                "path" : "http://res.freestockphotos.biz/pictures/17/17321-a-bowl-of-rice-with-chopsticks-pv.jpg",
                            },
                        ],
                        "license": licenses.CC_BY,
                    },
                ]
            },
        ]
    },
    {
        "title": "Rice Cookers",
        "id": "d98752",
        "description": "Start cooking rice today!",
        "children": [
            {
                "title": "Rice Chef",
                "id": "6cafe2",
                "author": "Revision 3",
                "description": "Become a master rice cooker",
                "file": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4",
                "license": licenses.CC_BY_NC_SA,
                "files": [
                    {
                        "path": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4",
                    },
                    {
                        "path": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg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Ax/VysS/vLq/zNwfArDhxMfExMXE3pMCMe7byMjIzd33ZgYGQtnz6+zooeJXBQMFD1yHejZ1+l8FBgEELlOR+GgFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=",
                    },
                ],
            },
            {
                "title": "Rice Exercise",
                "id": "6cafe3",
                "description": "Test how well you know your rice",
                "license": licenses.CC_BY_NC_SA,
                "mastery_model": exercises.M_OF_N,
                "files": [
                    {
                        "path": "http://www.publicdomainpictures.net/pictures/110000/nahled/bowl-of-rice.jpg",
                    }
                ],
                "questions": [
                    {
                        "id": "eeeee",
                        "question": "Which rice is your favorite? ![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAA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gFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=)",
                        "type":exercises.MULTIPLE_SELECTION,
                        "correct_answers": ["White rice", "Brown rice", "Sushi rice"],
                        "all_answers": ["White rice", "Quinoa","Brown rice"],
                    },
                    {
                        "id": "bbbbb",
                        "question": "Which rice is the crunchiest?",
                        "type":exercises.SINGLE_SELECTION,
                        "correct_answer": "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)",
                        "all_answers": ["White rice \n![](https://upload.wikimedia.org/wikipedia/commons/4/4b/Thai_jasmine_rice_uncooked.jpg)", "Brown rice \n![](https://c2.staticflickr.com/4/3159/2889140143_b99fd8dd4c_z.jpg?zz=1)", "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)"],
                        "hints": "It's delicious",
                    },
                    {
                        "id": "ccccc",
                        "question": "Why a rice cooker?",
                        "type":exercises.FREE_RESPONSE,
                        "answers": [],
                        "images": None,
                    },
                    {
                        "id": "aaaaa",
                        "question": "How many minutes does it take to cook rice? ![](https://upload.wikimedia.org/wikipedia/commons/5/5e/Jeera-rice.JPG)",
                        "type":exercises.INPUT_QUESTION,
                        "answers": ["20", "25", "15"],
                        "hints": ["Takes roughly same amount of time to install kolibri on Windows machine", "Does this help?\n![](http://www.aroma-housewares.com/images/rice101/delay_timer_1.jpg)"],
                    },
                    {
                        "id": "ddddd",
                        "type":exercises.PERSEUS_QUESTION,
                        "item_data":SAMPLE_PERSEUS,
                    },
                ],
            },
            {
                "title": "Rice Exercise 2",
                "id": "6cafe4",
                "description": "Test how well you know your rice",
                "license": licenses.CC_BY_NC_SA,
                "mastery_model": exercises.M_OF_N,
                "files": [
                    {
                        "path": "https://c1.staticflickr.com/5/4021/4302326650_b11f0f0aaf_b.jpg",
                    }
                ],
                "questions": [
                    {
                        "id": "11111",
                        "question": "<h3 id=\"rainbow\" style=\"font-weight:bold\">RICE COOKING!!!</h3><script type='text/javascript'><!-- setInterval(function() {$('#rainbow').css('color', '#'+((1<<24)*Math.random()|0).toString(16));}, 300); --></script>",
                        "type":exercises.SINGLE_SELECTION,
                        "all_answers": ["Answer"],
                        "correct_answer": "Answer",
                    },
                    {
                        "id": "121212",
                        "question": '<math> <mrow> <msup><mi> a </mi><mn>2</mn></msup> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> <mo> = </mo> <msup><mi> c </mi><mn>2</mn></msup> </mrow> </math>',
                        "type":exercises.SINGLE_SELECTION,
                        "all_answers": ["Answer"],
                        "correct_answer": "Answer",
                    },
                ],
            },
            {
                "title": "HTML Sample",
                "id": "abcdef",
                "description": "An example of how html can be imported from the ricecooker",
                "license": licenses.PUBLIC_DOMAIN,
                "files": [
                    {
                        "path": "C:/users/jordan/Videos/testfolder/htmltest.zip",
                    }
                ]
            },
            {
                "title": "Rice Exercise 3",
                "id": "6cafe5",
                "description": "Test how well you know your rice",
                "license": licenses.CC_BY_NC_SA,
                "mastery_model": exercises.M_OF_N,
                "files": [
                    {
                        "path": "https://upload.wikimedia.org/wikipedia/commons/b/b7/Rice_p1160004.jpg",
                    }
                ],
                "questions": [
                    {
                        "id": "ccccc",
                        "question": "<p><img align=\"middle\" alt=\"C o n s i d e r space t h e space f o l l o w i n g space f i g u r e space o f space l i n e space top enclose M N end enclose. space S a y space w h e t h e r space f o l l o w i n g space\r\ns t a t e m e n t s space a r e space t r u e space o r space f a l s e space i n space c o n t e x t space o f space t h e space g i v e n space f i g u r e.\r\n\" class=\"Wirisformula\" data-mathml=\"«math xmlns=¨http://www.w3.org/1998/Math/MathML¨»«mi»C«/mi»«mi»o«/mi»«mi»n«/mi»«mi»s«/mi»«mi»i«/mi»«mi»d«/mi»«mi»e«/mi»«mi»r«/mi»«mo»§#160;«/mo»«mi»t«/mi»«mi»h«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»f«/mi»«mi»o«/mi»«mi»l«/mi»«mi»l«/mi»«mi»o«/mi»«mi»w«/mi»«mi»i«/mi»«mi»n«/mi»«mi»g«/mi»«mo»§#160;«/mo»«mi»f«/mi»«mi»i«/mi»«mi»g«/mi»«mi»u«/mi»«mi»r«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»o«/mi»«mi»f«/mi»«mo»§#160;«/mo»«mi»l«/mi»«mi»i«/mi»«mi»n«/mi»«mi»e«/mi»«mo»§#160;«/mo»«menclose notation=¨top¨»«mi»M«/mi»«mi»N«/mi»«/menclose»«mo».«/mo»«mo»§#160;«/mo»«mi»S«/mi»«mi»a«/mi»«mi»y«/mi»«mo»§#160;«/mo»«mi»w«/mi»«mi»h«/mi»«mi»e«/mi»«mi»t«/mi»«mi»h«/mi»«mi»e«/mi»«mi»r«/mi»«mo»§#160;«/mo»«mi»f«/mi»«mi»o«/mi»«mi»l«/mi»«mi»l«/mi»«mi»o«/mi»«mi»w«/mi»«mi»i«/mi»«mi»n«/mi»«mi»g«/mi»«mo»§#160;«/mo»«mspace linebreak=¨newline¨/»«mi»s«/mi»«mi»t«/mi»«mi»a«/mi»«mi»t«/mi»«mi»e«/mi»«mi»m«/mi»«mi»e«/mi»«mi»n«/mi»«mi»t«/mi»«mi»s«/mi»«mo»§#160;«/mo»«mi»a«/mi»«mi»r«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»t«/mi»«mi»r«/mi»«mi»u«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»o«/mi»«mi»r«/mi»«mo»§#160;«/mo»«mi»f«/mi»«mi»a«/mi»«mi»l«/mi»«mi»s«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»i«/mi»«mi»n«/mi»«mo»§#160;«/mo»«mi»c«/mi»«mi»o«/mi»«mi»n«/mi»«mi»t«/mi»«mi»e«/mi»«mi»x«/mi»«mi»t«/mi»«mo»§#160;«/mo»«mi»o«/mi»«mi»f«/mi»«mo»§#160;«/mo»«mi»t«/mi»«mi»h«/mi»«mi»e«/mi»«mo»§#160;«/mo»«mi»g«/mi»«mi»i«/mi»«mi»v«/mi»«mi»e«/mi»«mi»n«/mi»«mo»§#160;«/mo»«mi»f«/mi»«mi»i«/mi»«mi»g«/mi»«mi»u«/mi»«mi»r«/mi»«mi»e«/mi»«mo».«/mo»«mspace linebreak=¨newline¨/»«/math»\" src=\"http://www.magogenie.com/assets/tinymce/jscripts/tiny_mce/plugins/tiny_mce_wiris/integration/showimage.php?formula=5ae94c3870f7867b485830ce79504b42.png\"><img src=\"data:image/jpeg;base64, \"></p><p><img src=\"http://www.magogenie.com/assets/tinymce/jscripts/tiny_mce/plugins/tiny_mce_wiris/integration/showimage.php?formula=f56752af6b14e80159ccc7de1100cb5b.png\" data-mathml=\"«math xmlns=¨http://www.w3.org/1998/Math/MathML¨»«mi»M«/mi»«mo»§#160;«/mo»«mi»i«/mi»«mi»s«/mi»«mo»§#160;«/mo»«mi»p«/mi»«mi»o«/mi»«mi»i«/mi»«mi»n«/mi»«mi»t«/mi»«mo»§#160;«/mo»«mi»o«/mi»«mi»n«/mi»«mo»§#160;«/mo»«mi»r«/mi»«mi»a«/mi»«mi»y«/mi»«mo»§#160;«/mo»«menclose notation=¨top¨»«mi»O«/mi»«mi»P«/mi»«/menclose»«/math»\" class=\"Wirisformula\" alt=\"M space i s space p o i n t space o n space r a y space top enclose O P end enclose\" align=\"middle\"><br></p>",
                        "type":exercises.SINGLE_SELECTION,
                        "all_answers": ["Yes", "No", "Rice!"],
                        "correct_answer": "Rice!",
                    },
                    {
                        "id": "ccdcc",
                        "question": "Solve this: $$(111^{x+1}\\times111^\\frac14)\\div111^\\frac12=111^3$$",
                        "type":exercises.SINGLE_SELECTION,
                        "all_answers": ["Yes", "No", "Rice!"],
                        "correct_answer": "Rice!",
                    },
                ],
            },
        ]
    },
]

def construct_channel(**kwargs):

    channel = nodes.ChannelNode(
        source_domain="learningequality.org",
        source_id="testing-ricecooker-channel",
        title="Testing Ricecooker Channel",
        thumbnail="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Banaue_Philippines_Banaue-Rice-Terraces-01.jpg/640px-Banaue_Philippines_Banaue-Rice-Terraces-01.jpg",
    )

    _build_tree(channel, SAMPLE_TREE)
    raise_for_invalid_channel(channel)

    return channel


def _build_tree(node, sourcetree):

    for child_source_node in sourcetree:
        try:
            files = [f['path'] for f in child_source_node['files']] if 'files' in child_source_node else None
            kind = nodes.guess_content_kind(files, child_source_node.get("questions"))
        except UnknownContentKindError:
            continue

        if kind == content_kinds.TOPIC:
            child_node = nodes.TopicNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
            )
            node.add_child(child_node)

            source_tree_children = child_source_node.get("children", [])

            _build_tree(child_node, source_tree_children)

        elif kind == content_kinds.VIDEO:
            child_node = nodes.VideoNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                license=child_source_node.get("license"),
                derive_thumbnail=True, # video-specific data
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.AUDIO:
            child_node = nodes.AudioNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                license=child_source_node.get("license"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.DOCUMENT:
            child_node = nodes.DocumentNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                license=child_source_node.get("license"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.EXERCISE:
            child_node = nodes.ExerciseNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                exercise_data={}, # Just set to default
                license=child_source_node.get("license"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            for q in child_source_node.get("questions"):
                question = create_question(q)
                child_node.add_question(question)
            node.add_child(child_node)

        elif kind == content_kinds.HTML5:
            child_node = nodes.HTML5AppNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                license=child_source_node.get("license"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        else:                   # unknown content file format
            continue

    return node

def add_files(node, file_list):
    for f in file_list:
        file_type = guess_file_type(f['path'], node.kind)

        if file_type == FileTypes.AUDIO_FILE:
            node.add_file(files.AudioFile(path=f['path'], language=f.get('language')))
        elif file_type == FileTypes.THUMBNAIL:
            node.add_file(files.ThumbnailFile(path=f['path']))
        elif file_type == FileTypes.DOCUMENT_FILE:
            node.add_file(files.DocumentFile(path=f['path'], language=f.get('language')))
        elif file_type == FileTypes.HTML_ZIP_FILE:
            node.add_file(files.HTMLZipFile(path=f['path'], language=f.get('language')))
        elif file_type == FileTypes.VIDEO_FILE:
            node.add_file(files.VideoFile(path=f['path'], language=f.get('language'), ffmpeg_settings=f.get('ffmpeg_settings')))
        elif file_type == FileTypes.SUBTITLE_FILE:
            node.add_file(files.SubtitleFile(path=f['path'], language=f['language']))
        elif file_type == FileTypes.BASE64_FILE:
            node.add_file(files.Base64ImageFile(encoding=f['path']))
        else:
            raise UnknownFileTypeError("Unrecognized file type '{0}'".format(f['path']))

def create_question(raw_question):

    if raw_question["type"] == exercises.MULTIPLE_SELECTION:
        return questions.MultipleSelectQuestion(
            id=raw_question["id"],
            question=raw_question["question"],
            correct_answers=raw_question["correct_answers"],
            all_answers=raw_question["all_answers"],
            hints=raw_question.get("hints"),
        )
    if raw_question["type"] == exercises.SINGLE_SELECTION:
        return questions.SingleSelectQuestion(
            id=raw_question["id"],
            question=raw_question["question"],
            correct_answer=raw_question["correct_answer"],
            all_answers=raw_question["all_answers"],
            hints=raw_question.get("hints"),
        )
    if raw_question["type"] == exercises.INPUT_QUESTION:
        return questions.InputQuestion(
            id=raw_question["id"],
            question=raw_question["question"],
            answers=raw_question["answers"],
            hints=raw_question.get("hints"),
        )
    if raw_question["type"] == exercises.FREE_RESPONSE:
        return questions.FreeResponseQuestion(
            id=raw_question["id"],
            question=raw_question["question"],
            hints=raw_question.get("hints"),
        )
    if raw_question["type"] == exercises.PERSEUS_QUESTION:
        return questions.PerseusQuestion(
            id=raw_question["id"],
            raw_data=raw_question["item_data"],
        )
    else:
        raise UnknownQuestionTypeError("Unrecognized question type '{0}': accepted types are {1}".format(raw_question["type"], [key for key, value in exercises.question_choices]))
