using System;

namespace InABox.DigitalMatter
{
    public interface IDMObject
    {
        void Decode(byte[] data);
        byte[] Encode();
    }

    public abstract class DMObject : DMBuffer, IDMObject
    {
        public void Decode(byte[] data)
        {
            Buffer = data;
            BeforeDecode();
            DoDecode();
            AfterDecode();
        }

        public byte[] Encode()
        {
            Reset();
            BeforeEncode();
            DoEncode();
            AfterEncode();
            return Buffer;
        }

        protected uint SecondsSince2013UTC()
        {
            var epoch = new DateTime(2013, 1, 1);
            var utc = DateTime.Now.ToUniversalTime();
            var elapsed = utc - epoch;
            return (uint)elapsed.TotalSeconds;
        }

        public DateTime TimeStampToDateTime(uint timestamp)
        {
            return new DateTime(2013, 1, 1).AddSeconds(timestamp).ToLocalTime();
        }

        protected virtual void BeforeEncode()
        {
        }

        protected abstract void DoEncode();

        protected virtual void AfterEncode()
        {
        }

        protected virtual void BeforeDecode()
        {
        }

        protected abstract void DoDecode();

        protected virtual void AfterDecode()
        {
        }
    }
}