using System;

namespace InABox.Core
{
    public enum CoreRangeType
    {
        /// <summary>
        /// Get specific range in the database query.
        /// </summary>
        Database, 
        /// <summary>
        /// Get everything from the database, but only return a small number to the client.
        /// </summary>
        Paged
    }
    public class CoreRange : ISerializeBinary
    {
        public static CoreRange All => new CoreRange()
        {
            Type = CoreRangeType.Database,
            Offset = 0,
            Limit = int.MaxValue
        };
        
        public static CoreRange Database(int limit) => new CoreRange()
        {
            Type = CoreRangeType.Database,
            Offset = 0,
            Limit = limit
        };

        public static CoreRange Paged(int pagesize) => new CoreRange()
        {
            Type = CoreRangeType.Paged,
            Offset = 0,
            Limit = pagesize
        };

        public CoreRange Next()
        {
            Offset = (int)Math.Min((long)int.MaxValue, (long)Offset + (long)Limit);
            return this;
        }      
        
        public CoreRangeType Type { get; set; }
        public int Offset { get; set; }
        public int Limit { get; set; }
        
        public void SerializeBinary(CoreBinaryWriter writer)
        {
            writer.Write((byte)Type);
            writer.Write(Offset);
            writer.Write(Limit);
        }

        public void DeserializeBinary(CoreBinaryReader reader)
        {
            Type = (CoreRangeType)reader.ReadByte();
            Offset = reader.ReadInt32();
            Limit = reader.ReadInt32();
        }
    }
}