using CPF.Drawing;
using ESBasic;
using System;
using System.IO;

namespace OVCS.ClientLinux.Tools
{
    internal class ExtenseCompactPropertySerializer  
    {
        protected bool CustomizeExtenseDeserialize(Type type, byte[] buff, ref int offset, out object obj)
        {
            obj = null;
            if (type == typeof(Image))
            {
                int len = ByteConverter.Parse<int>(buff, ref offset);
                Image bitmap = null;
                if (len > -1)
                {
                    offset += 1;
                    byte[] imgBuff = new byte[len];
                    Buffer.BlockCopy(buff, offset, imgBuff, 0, len);
                    MemoryStream ms = new MemoryStream(imgBuff);
                    bitmap = Image.FromStream(ms);
                    offset += len;
                }
                obj = bitmap;
                return true;
            }
            return false;
        }

        protected bool CustomizeExtenseSerialize(MemoryStream stream, Type type, object obj)
        {
            if (type == typeof(Image))
            {
                if (obj == null)
                {
                    byte[] buff = ByteConverter.ToBytes<int>(-1);
                    stream.Write(buff, 0, buff.Length);
                }
                else
                {
                    byte[] val2 = BitmapHelper.Bitmap2Byte((Image)obj); 
                    byte[] len = ESBasic.ByteConverter.ToBytes<int>(val2.Length);
                    stream.Write(len, 0, len.Length);
                    stream.Write(BitConverter.GetBytes(false), 0, 1);
                    stream.Write(val2, 0, val2.Length);
                }
                return true;
            }
            return false;
        }
    }
}
