#!/usr/bin/env python2.7
from __future__ import print_function

import errno
import os
from glob import glob

FILE_EXTENSION_BY_LANGUAGE = {
    'bash': 'sh',
    'C': 'c',
    'C#': 'cs',
    'C++': 'cpp',
    'go': 'go',
    'java': 'java',
    'powershell': 'ps1',
    'python': 'py',
    'R': 'R',
}

def import_lesson(lesson_file_path):
    with open(lesson_file_path) as lesson_file:
        for line in lesson_file:
            if line.startswith('```'):
                write_output(lesson_file, line[3:].split()[0])
                return


def write_output(lesson_file, language):
    extension = FILE_EXTENSION_BY_LANGUAGE.get(language)
    if not extension:
        return
    path_parts = lesson_file_path.split('/')
    chapter = os.path.join('projects', extension, path_parts[1])
    try:
        os.makedirs(chapter)
    except OSError as error:
        if error.errno != errno.EEXIST:
            raise
    file_name = os.path.splitext(path_parts[2])[0] + '.' + extension
    file_name = file_name[file_name.find('-') + 1:]  # remove prefix
    with open(os.path.join(chapter, file_name), 'w') as output_file:
        for code_line in lesson_file:
            if code_line == '```\n':
                return
            output_file.write(code_line)


if __name__ == '__main__':
    for lesson_file_path in glob('markdowns/*/*.md'):
        import_lesson(lesson_file_path)
        print('imported code from', lesson_file_path)
