﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerVue.JsonModels
{
    public class JsonObject : JsonToken, IJsonObject
    {
        private Dictionary<String, Object> map = new Dictionary<string, object>();

        public JsonObject(Dictionary<String, Object> map)
        {
            if (map == null) map = new Dictionary<string, object>();
            this.map = map;
        }

        public JsonObject() : this(new Dictionary<string, object>())
        {

        }

        internal override object StringifyTarget => map;

        public IJsonArray GetArray(string propertyName)
        {
            Object value = null;
            if (!this.map.TryGetValue(propertyName, out value))
            {
                List<Object> array = new List<object>();
                this.map[propertyName] = array;
                return new JsonArray(array);
            }

            if (value is Object[])
            {
                List<Object> array = (value as Object[]).ToList<Object>();
                this.map[propertyName] = array;
                return new JsonArray(array);
            }

            if (!(value is List<Object>))
                throw new InvalidCastException();

            return new JsonArray(value as List<Object>);
        }

        public IJsonObject GetObject(string propertyName)
        {
            Object value = null;
            if (this.map.TryGetValue(propertyName, out value))
            {
                if (value is Dictionary<String, Object>)
                {
                    return new JsonObject((Dictionary<String, Object>)value);
                }
                else
                {
                    throw new InvalidCastException();
                }
            }
            else
            {
                Dictionary<String, Object> subMap = new Dictionary<string, object>();
                this.map[propertyName] = subMap;
                return new JsonObject(subMap);
            }
        }

        public IJsonValue GetValue(string propertyName)
        {
            Object value = null;
            this.map.TryGetValue(propertyName, out value);
            return new JsonValue(value);
        }

        public void Set(string propertyName, IJsonToken value)
        {
            this.map[propertyName] = this.AsJsonToken(value).StringifyTarget;
        }
    }
}
