using System;
using System.Net;
using InABox.Core;

namespace InABox.Rpc
{
    public class RpcQueryDefinition : ISerializeBinary
    {
        public string Key { get; set; }
        public Type Type { get; set; }
        public IFilter? Filter { get; set; }
        public IColumns? Columns { get; set; }
        public ISortOrder? Sort { get; set; }
        
        public CoreRange? Range { get; set; }
        
        public void SerializeBinary(CoreBinaryWriter writer)
        {
            writer.Write(Key ?? string.Empty);
            writer.Write(Type.EntityName());

            writer.WriteBinaryValue(Filter);
            writer.WriteBinaryValue(Columns);
            writer.WriteBinaryValue(Sort);
            writer.WriteBinaryValue(Range);
        }

        public void DeserializeBinary(CoreBinaryReader reader)
        {
            Key = reader.ReadString();

            Type = CoreUtils.GetEntity(reader.ReadString());
            Filter = reader.ReadBinaryValue(typeof(Filter<>).MakeGenericType(Type)) as IFilter;
            Columns = reader.ReadBinaryValue(typeof(Columns<>).MakeGenericType(Type)) as IColumns;
            Sort = reader.ReadBinaryValue(typeof(SortOrder<>).MakeGenericType(Type)) as ISortOrder;
            Range = reader.ReadBinaryValue<CoreRange>();
        }

        public string FullDescription() => $"[{Filter}]";

        public string ShortDescription() => $"Query";
    }
}