# -*- coding: utf8 -*-
"""
Copyright 2014 Ryan Brown <sb@ryansb.com>

This file is part of bookmarkd.

bookmarkd is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

bookmarkd is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with bookmarkd.  If not, see <http://www.gnu.org/licenses/>.
"""

import json
from os.path import basename

import CommonMark as markdown
from IPython.nbformat import current


def to_notebook(infile):
    """Given markdown, returns an ipynb compliant JSON string"""

    parser = markdown.DocParser()
    ast = json.loads(markdown.ASTtoJSON(
        parser.parse(infile.read())))

    cells = []

    for block in ast.get('children', []):
        if block['t'] in ["IndentedCode", "FencedCode"]:
            cells.append(current.new_code_cell(block['string_content']))
        else:
            cells.append(current.new_text_cell(
                'markdown',
                '\n'.join(block['strings']))
            )

    worksheet = current.new_worksheet(cells=cells)

    nb = current.new_notebook(
        basename(infile.name).split('.')[:-1],
        worksheets=[worksheet]
    )

    return json.dumps(nb, indent=2)

@@ -1225,24 +1225,362 @@
 content'%5D))%0A
+        elif block%5B't'%5D in %5B'SetextHeader', 'ATXHeader'%5D:%0A            cells.append(current.new_text_cell(%0A                'markdown',%0A                '#' * block.get('level', 1) + ' ' + ''.join(block%5B'strings'%5D))%0A            )%0A        elif block%5B't'%5D in %5B'HorizontalRule'%5D:%0A            # We don't render horizontal rules%0A            pass%0A
         else

Add handling of multiple header levels