"""
Grew module : anything you want to talk about graphs
Graphs are represented either by a dict (called dict-graph),
or by an str (str-graph).
"""
import os.path
import re
import copy
import tempfile
import json

import utils
import network
import ast

''' Library tools '''

def init():
    """
    Initialize connection to GREW library
    :return: True if anything went right
    """
    return network.init()

def grs(grsystem):
    """Load a grs stored in a file
    :param grs: either a file name or a GREW string representation of a grs
    :raise an error if the file was not correctly loaded
    """
    if os.path.isfile(grsystem):
        req = { "command": "load_grs", "filename": grsystem }
        reply = network.send_and_receive(req)
    else:
        with tempfile.NamedTemporaryFile(mode="w", delete=True) as f:
            f.write(grsystem)
            f.seek(0)  # to be read by others
            req = { "command": "load_grs", "filename": fname }
            reply = network.send_and_receive(req)
    return reply["index"]

def run(rs, gr, strat="main"):
    """
    Apply rs or the last loaded one to [gr]
    :param gr: the graph, either a str (in grew format) or a dict
    :param rs: a graph rewriting
     system or a GREW string representation of a grs
    :param strategy: the strategy. By default, !
    :return: the list of rewritten graphs
    """
    req = {
        "command": "run",
        "graph": json.dumps(gr),
        "grs_index": rs,
        "strat": strat
    }
    reply = network.send_and_receive(req)
    return reply

def search(pattern, gr):
    """
    Search for [pattern] into [gr]
    :param patten: a string pattern
    :param gr: the graph
    :return: the list of matching of [pattern] into [gr]
    """
    req = {
        "command": "search",
        "graph": json.dumps(gr),
        "pattern": pattern
    }
    reply = network.send_and_receive(req)
    return reply

def json_grs(rs):
    req = { "command": "json_grs", "grs_index": rs }
    return network.send_and_receive(req)

def dot_graph(gr):
    req = { "command": "dot_graph", "graph": json.dumps(gr) }
    return network.send_and_receive(req)

