# encoding: utf-8
"""
Read graphs in GML format.

"GML, the G>raph Modelling Language, is our proposal for a portable
file format for graphs. GML's key features are portability, simple
syntax, extensibility and flexibility. A GML file consists of a
hierarchical key-value lists. Graphs can be annotated with arbitrary
data structures. The idea for a common file format was born at the
GD'95; this proposal is the outcome of many discussions. GML is the
standard file format in the Graphlet graph editor system. It has been
overtaken and adapted by several other systems for drawing graphs."

See http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html

Format
------
See http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
for format specification.

Example graphs in GML format:
http://www-personal.umich.edu/~mejn/netdata/

"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
#    Copyright (C) 2008-2010 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.

__all__ = ['read_gml', 'parse_gml', 'generate_gml', 'write_gml']

try:
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO
except ImportError:
    from io import StringIO
from ast import literal_eval
from collections import defaultdict
from lib2to3.pgen2.parse import ParseError
from lib2to3.pgen2.tokenize import TokenError
from lib2to3.refactor import RefactoringTool
import networkx as nx
from networkx.exception import NetworkXError
from networkx.utils import open_file

import re
try:
    import htmlentitydefs
except ImportError:
    # Python 3.x
    import html.entities as htmlentitydefs

try:
    long
except NameError:
    long = int
try:
    unicode
except NameError:
    unicode = str
try:
    unichr
except NameError:
    unichr = chr
try:
    literal_eval(r"u'\u4444'")
except SyntaxError:
    # Remove 'u' prefixes in unicode literals in Python 3
    rtp_fix_unicode = RefactoringTool(['lib2to3.fixes.fix_unicode'],
                                      {'print_function': True})
else:
    rtp_fix_unicode = None


def escape(text):
    """Escape unprintable or non-ASCII characters, double quotes and ampersands
    in a string using XML character references.
    """
    def fixup(m):
        ch = m.group(0)
        return '&#' + str(ord(ch)) + ';'

    text = re.sub('[^ -~]|[&"]', fixup, text)
    return text if isinstance(text, str) else str(text)


def unescape(text):
    """Replace XML character references in a string with the referenced
    characters.
    """
    def fixup(m):
        text = m.group(0)
        if text[1] == '#':
            # Character reference
            if text[2] == 'x':
                code = int(text[3:-1], 16)
            else:
                code = int(text[2:-1])
        else:
            # Named entity
            try:
                code = htmlentitydefs.name2codepoint[text[1:-1]]
            except KeyError:
                return text  # leave unchanged
        try:
            return chr(code) if code < 256 else unichr(code)
        except (ValueError, OverflowError):
            return text  # leave unchanged

    return re.sub("&(?:[0-9A-Za-z]+|#(?:[0-9]+|x[0-9A-Fa-f]+));", fixup, text)


def literal_destringizer(rep):
    """Convert a Python literal to the value it represents.

    Parameters
    ----------
    rep : string
        A Python literal.

    Returns
    -------
    value : object
        The value of the Python literal.

    Raises
    ------
    ValueError
        If ``rep`` is not a Python literal.
    """
    if isinstance(rep, (str, unicode)):
        orig_rep = rep
        try:
            # Python 3.2 does not recognize 'u' prefixes before string literals
            if rtp_fix_unicode:
                rep = str(rtp_fix_unicode.refactor_string(
                    rep + '\n', '<string>'))[:-1]
            return literal_eval(rep)
        except (ParseError, SyntaxError, TokenError):
            raise ValueError('%r is not a valid Python literal' % (orig_rep,))
    else:
        raise ValueError('%r is not a string' % (rep,))


@open_file(0, mode='rb')
def read_gml(path, label='label', destringizer=None):
    """Read graph in GML format from path.

    Parameters
    ----------
    path : filename or filehandle
        The filename or filehandle to read from.

    label : string, optional
        If not None, the parsed nodes will be renamed according to node
        attributes indicated by ``label``. Default value: ``'label'``.

    destringizer : callable, optional
        A destringizer that recovers values stored as strings in GML. If it
        cannot convert a string to a value, a ``ValueError`` is raised. Default
        value : ``None``.

    Returns
    -------
    G : NetworkX graph
        The parsed graph.

    Raises
    ------
    NetworkXError
        If the input cannot be parsed.

    See Also
    --------
    write_gml, parse_gml

    Notes
    -----
    The GML specification says that files should be ASCII encoded, with any
    extended ASCII characters (iso8859-1) appearing as HTML character entities.

    References
    ----------
    GML specification:
    http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gml(G, 'test.gml')
    >>> H = nx.read_gml('test.gml')
    """
    def filter_lines(lines):
        for line in lines:
            try:
                line = line.decode('ascii')
            except UnicodeDecodeError:
                raise NetworkXError('input is not ASCII-encoded')
            if not isinstance(line, str):
                lines = str(lines)
            if line and line[-1] == '\n':
                line = line[:-1]
            yield line

    G = parse_gml_lines(filter_lines(path), label, destringizer)
    return G


def parse_gml(lines, label='label', destringizer=None):
    """Parse GML graph from a string or iterable.

    Parameters
    ----------
    lines : string or iterable of strings
       Data in GML format.

    label : string, optional
        If not None, the parsed nodes will be renamed according to node
        attributes indicated by ``label``. Default value: ``'label'``.

    destringizer : callable, optional
        A destringizer that recovers values stored as strings in GML. If it
        cannot convert a string to a value, a ``ValueError`` is raised. Default
        value : ``None``.

    Returns
    -------
    G : NetworkX graph
        The parsed graph.

    Raises
    ------
    NetworkXError
        If the input cannot be parsed.

    See Also
    --------
    write_gml, read_gml

    Notes
    -----
    This stores nested GML attributes as dictionaries in the
    NetworkX graph, node, and edge attribute structures.

    References
    ----------
    GML specification:
    http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
    """
    def decode_line(line):
        if isinstance(line, bytes):
            try:
                line.decode('ascii')
            except UnicodeDecodeError:
                raise NetworkXError('input is not ASCII-encoded')
        if not isinstance(line, str):
            line = str(line)
        return line

    def filter_lines(lines):
        if isinstance(lines, (str, unicode)):
            lines = decode_line(lines)
            lines = lines.splitlines()
            for line in lines:
                yield line
        else:
            for line in lines:
                line = decode_line(line)
                if line and line[-1] == '\n':
                    line = line[:-1]
                if line.find('\n') != -1:
                    raise NetworkXError('input line contains newline')
                yield line

    G = parse_gml_lines(filter_lines(lines), label, destringizer)
    return G


def parse_gml_lines(lines, label, destringizer):
    """Parse GML into a graph.
    """
    def tokenize():
        patterns = [
            r'[A-Za-z][0-9A-Za-z]*\s+',  # keys
            r'[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)(?:[Ee][+-]?[0-9]+)?',  # reals
            r'[+-]?[0-9]+',   # ints
            r'".*?"',         # strings
            r'\[',            # dict start
            r'\]',            # dict end
            r'#.*$|\s+'       # comments and whitespaces
            ]
        tokens = re.compile(
            '|'.join('(' + pattern + ')' for pattern in patterns))
        lineno = 0
        for line in lines:
            length = len(line)
            pos = 0
            while pos < length:
                match = tokens.match(line, pos)
                if match is not None:
                    for i in range(len(patterns)):
                        group = match.group(i + 1)
                        if group is not None:
                            if i == 0:    # keys
                                value = group.rstrip()
                            elif i == 1:  # reals
                                value = float(group)
                            elif i == 2:  # ints
                                value = int(group)
                            else:
                                value = group
                            if i != 6:    # comments and whitespaces
                                yield (i, value, lineno + 1, pos + 1)
                            pos += len(group)
                            break
                else: