using System.Collections.Generic;
using System.Linq;
using isnd.Data.Catalog;
using Newtonsoft.Json.Serialization;

namespace isnd
{
    internal class NSJWebApiReferenceResolver : IReferenceResolver
    {
          private int delautIdCounter;

        Dictionary<string, HappyIdOwner> HappyIdOwners { get; set; } 

        Dictionary<int,object> Objects {get; set;} 
        internal NSJWebApiReferenceResolver()
        {
            delautIdCounter = 0;
            HappyIdOwners = new Dictionary<string, HappyIdOwner>();
            Objects = new Dictionary<int, object>();
        }

        public void AddReference(object context, string reference, object value)
        {
             if (value is HappyIdOwner)
            {
                string hoi = (value as HappyIdOwner).GetId();
                if (HappyIdOwners.ContainsKey(hoi))
                {
                    return;
                }
                HappyIdOwners[hoi] = value as HappyIdOwner;
            }
            else
            {
                if (Objects.ContainsValue(value))
                {
                    return;
                }

                delautIdCounter++;
                Objects[delautIdCounter] = value;
            } 
        }

        public string GetReference(object context, object value)
        {
            bool alreadyExists;
             if (value is HappyIdOwner)
            {
                string oid = (value as HappyIdOwner).GetId();
                if (oid == null)
                    throw new System.Exception("HappyIdOwner Id property is null");
                if (HappyIdOwners.ContainsKey(oid))
                {
                    alreadyExists=true;
                    return oid;
                }
                alreadyExists=false;
                AddReference(context, oid, value);
                return oid;
            }
            alreadyExists=false;
           
            if (Objects.ContainsValue(value))
            {
                alreadyExists=true;
                return Objects.First( ode => ode.Value ==value).Key.ToString();
            }
            alreadyExists=false;
            delautIdCounter++;
            Objects[delautIdCounter]=value;
            return delautIdCounter.ToString();
        }

        public bool IsReferenced(object context, object value)
        {
            throw new System.NotImplementedException();
        }

        public object ResolveReference(object context, string reference)
        {
            throw new System.NotImplementedException();
        }
    }
}