﻿using System;
using System.Xml;
using XmlToTex.Source.DataStructures;
using XmlToTex.Source.Elements.Base;
using XmlToTex.Source.Elements.Interfaces;
using XmlToTex.Source.Serialization;
using XmlToTex.Source.Util.Extensions;

namespace XmlToTex.Source.Elements.Implementations.TerminalNodes
{
    public class Graph : Terminal, IGraph
    {
        private readonly TikzGraphSerializer _serializer = new TikzGraphSerializer();
        public override bool DisplayText => false;

        public override void BeforeAny(Document document)
        {
            var g = new DataStructures.Graph();

            foreach (XmlNode child in node.ChildNodes)
            {
                switch (child.Name)
                {
                    case "node":
                        Node(child, g);
                        break;
                    case "edge":
                        Edge(child, g);
                        break;
                }
            }

            document.AddPackage("tkz-graph");
            document.AddPackage("tikz");
            document.AddConfig(@"\usetikzlibrary{shapes,arrows}");
            document.AppendText(_serializer.Serialize(g));
        }

        private static void Edge(XmlNode node, DataStructures.Graph graph)
        {
            var from = node.Attribute("from");
            var to = node.Attribute("to");
            var label = node.Attribute("lbl");
            var col = node.Attribute("col");
            var directed = node.Attribute("directed");

            graph.AddEdge(from, to, label, col, directed == "true");
        }

        private static void Node(XmlNode node, DataStructures.Graph graph)
        {
            var label = node.Attribute("lbl");
            var id = node.Attribute("id");
            var xPos = int.Parse(node.Attribute("x"));
            var yPos = int.Parse(node.Attribute("y"));
            var col = node.Attribute("col");

            graph.AddNode(id ?? label, label, xPos, yPos, col);
        }
    }
}
