using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

using SimpleJSON;



namespace Assets
{

    public class Coord
    {
        public Coord(Int32 x = 0, Int32 y = 0)
        {
            X = x;
            Y = y;
        }

        public Int32 X { get; set; }


        public Int32 Y { get; set; }

        public static Coord FromString(JSONNode parsed)
        {
           
            var created = new Coord();
            created.X = parsed["X"].AsInt;
            created.Y = parsed["Y"].AsInt;
            return created;
        }

        public override string ToString()
        {
            var str = String.Format("X: {0} Y: {1}", X,Y);
            return str;
        }

    }

    public class Square
    {

        public Coord UL { get; set; }

        public Coord UR { get; set; }

        public Coord DR { get; set; }

        public Coord DL { get; set; }

        public override string ToString()
        {
            var str = String.Format("UL: {0} UR: {1} DR: {2} DL: {3}", UL, UR, DR, DL);
            return str;
        }

        public static Square FromString(JSONNode parsed)
        { 
            if (
                parsed["UL"] == null ||
                parsed["UR"] == null ||
                parsed["DL"] == null ||
                parsed["DR"] == null)
                return null;
            var created = new Square();

            created.UL = Coord.FromString(parsed["UL"]);
            created.UR = Coord.FromString(parsed["UR"]);
            created.DL = Coord.FromString(parsed["DL"]);
            created.DR = Coord.FromString(parsed["DR"]);
            return created;
        }
    }


    public class ControllMessage
    {

        public double Ticks { get; set; }

        public Square Square { get; set; }

        public String Error { get; set; }

        public static ControllMessage FromString(string aStr)
        {
            if (String.IsNullOrEmpty(aStr))
                return null;

            var created = new ControllMessage();
            var parsed = JSON.Parse(aStr);

            created.Ticks = parsed["Ticks"].AsDouble;

            created.Error = parsed["Error"].Value;

            if(parsed["Square"] != null)
            created.Square = Square.FromString(parsed["Square"]);

            return created;
        }

        public static String ToString(ControllMessage aMsg)
        {
            return JsonUtility.ToJson(aMsg);
        }

        public override string ToString()
        {
            var str = String.Format("Ticks: {0} Error {1} Square {2} ",Ticks, Error,Square);
            return str;
        }
    }

}
