#-*- coding: utf-8 -*-
import re, os
from os.path import join
from dmlt import events
from dmlt.machine import MarkupMachine, Directive, RawDirective, \
    rule, bygroups
from dmlt.utils import escape, strip_ext, parse_child_nodes, filter_stream, \
    load_tree, dump_tree
import nodes


# Some terms the lexer understands as URL.
# Note that this list is far from complete...
_url_pattern = (
    # urls with netloc
    r'(?:(?:https?|ftps?|file|ssh|mms|svn(?:\+ssh)?|git|dict|nntp|irc|'
    r'rsync|smb)://|'
    # urls without netloc
    r'(?:mailto|telnet|s?news|sips?|skype):)'
)


class TextDirective(RawDirective):
    name = 'text'

    def parse(self, stream):
        return nodes.Text(stream.expect('text').value)

@events.register('define-raw-directive')
def _handle_register_raw_directive(mnager, *args, **kwargs):
    return TextDirective


class StrongDirective(Directive):
    rule = rule(r'\*\*', enter='strong', leave='strong')

    def parse(self, stream):
        stream.expect('strong_begin')
        children = parse_child_nodes(stream, self, 'strong_end')
        stream.expect('strong_end')
        return nodes.Strong(children)


class UnderlineDirective(Directive):
    rule = rule(r'__', enter='underline', leave='underline')

    def parse(self, stream):
        stream.expect('underline_begin')
        children = parse_child_nodes(stream, self, 'underline_end')
        stream.expect('underline_end')
        return nodes.Underline(children)


class EmphasizedDirective(Directive):
    rule = rule(r"''", enter='emphasized', leave='emphasized')

    def parse(self, stream):
        stream.expect('emphasized_begin')
        children = parse_child_nodes(stream, self, 'emphasized_end')
        stream.expect('emphasized_end')
        return nodes.Emphasized(children)


class EscapedCodeDirective(Directive):
    rule = rule(r'\`\`', enter='escaped_code', leave='escaped_code')

    def parse(self, stream):
        stream.expect('escaped_code_begin')
        buffer = []
        while stream.current.type != 'escaped_code_end':
            buffer.append(stream.current.value)
            stream.next()
        stream.expect('escaped_code_end')
        return nodes.Code([nodes.Text(u''.join(buffer))])


class SubscriptDirective(Directive):
    rule = rule(r',,', enter='sub', leave='sub')

    def parse(self, stream):
        stream.expect('sub_begin')
        children = parse_child_nodes(stream, self, 'sub_end')
        stream.expect('sub_end')
        return nodes.Sub(children)


class SuperscriptDirective(Directive):
    rules = [
        rule(r'\^\^\(', enter='sup'),
        rule(r'\)\^\^', leave='sup')]

    def parse(self, stream):
        stream.expect('sup_begin')
        children = parse_child_nodes(stream, self, 'sup_end')
        stream.expect('sup_end')
        return nodes.Sup(children)


class StrokeDirective(Directive):
    rules = [
        rule(r'~~\(', enter='stroke'),
        rule(r'\)~~', leave='stroke')]