import sys

sys.path.append("interface/plot/")
sys.path.append("wrappers/")

from MatPlotLibWrapper import *
from plot import *
from modelverse import *
import uuid

# Login to Modelverse and have model rendered
init()
login("admin", "admin")
rendered = model_render(sys.argv[1], "models/trace_mapper", "rendered/%s" % str(uuid.uuid4()))

# Convert rendered to "MatPlotLib JSON"
data = rendered
plots = {}
axis = {}
datasets = {}
datapoints = {}

for elem in data:
    # Nodes
    if elem["type"] == "Plot":
        plot = Plot([])
        plot.legend = elem["legend"]
        plot.title = elem["title"]
        plots[elem["id"]] = plot
    elif elem["type"] == "Dataset":
        dataset = DataSet([])
        dataset.color = elem["color"]
        dataset.linestyle = elem["linestyle"]
        dataset.legend = elem["legend"]
        datasets[elem["id"]] = dataset
    elif elem["type"] == "XAxis":
        xaxis = XAxis()
        xaxis.name = elem["name"]
        xaxis.unit = elem["unit"]
        xaxis.lim_low = elem["lim_low"] if "lim_low" in elem else None
        xaxis.lim_high = elem["lim_high"] if "lim_high" in elem else None
        axis[elem["id"]] = xaxis
    elif elem["type"] == "YAxis":
        yaxis = YAxis()
        yaxis.name = elem["name"]
        yaxis.unit = elem["unit"]
        yaxis.lim_low = elem["lim_low"] if "lim_low" in elem else None
        yaxis.lim_high = elem["lim_high"] if "lim_high" in elem else None
        axis[elem["id"]] = yaxis
    elif elem["type"] == "Datapoint":
        datapoint = DataPoint(elem["x"], elem["y"])
        datapoints[elem["id"]] = datapoint

    # Edges
    elif elem["type"] == "x":
        plot = plots[elem["__source"]]
        xaxis = axis[elem["__target"]]
        plot.x = xaxis
    elif elem["type"] == "y":
        plot = plots[elem["__source"]]
        yaxis = axis[elem["__target"]]
        plot.y = yaxis
    elif elem["type"] == "data":
        plot = plots[elem["__source"]]
        dataset = datasets[elem["__target"]]
        plot.datasets.append(dataset)
    elif elem["type"] == "point":
        dataset = datasets[elem["__source"]]
        point = datapoints[elem["__target"]]
        dataset.datapoints.append(point)

# Call library
MatPlotLibWrapper().visualize([plot.to_json() for plot in plots.values()])
