using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace AT288Demo.Net.Custom
{
    public partial class TransparentPanel : Panel
    {
        #region Member variable
        private Image m_Image;
        private Color m_MaskColor;
        #endregion

        #region Constructoer
        public TransparentPanel()
        {
            m_Image = null;
            m_MaskColor = Color.White;
        }
        #endregion

        #region Properties
        public Image Image
        {
            get { return m_Image; }
            set
            {
                m_Image = value;
                if (m_Image != null)
                {
                    ImageAnimator.Animate(m_Image, new EventHandler(this.OnFrameChanged));
                }
            }
        }

        public Color MaskColor
        {
            get { return m_MaskColor; }
            set { m_MaskColor = value; }
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT
                return cp;
            }
        }
        #endregion

        #region Overrid Event Method
        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (m_Image != null)
            {
                ImageAnimator.UpdateFrames();

                Bitmap bmp = new Bitmap(m_Image.Width, m_Image.Height);
                Graphics gg = Graphics.FromImage(bmp);
                gg.Clear(this.m_MaskColor);
                gg.DrawImage(m_Image, new Point(0, 0));
                ImageAttributes attr = new ImageAttributes();
                int x = (ClientSize.Width / 2) - (m_Image.Width / 2);
                int y = (ClientSize.Height / 2) - (m_Image.Height / 2);
                Rectangle rect = new Rectangle(x, y, m_Image.Width, m_Image.Height);
                attr.SetColorKey(this.m_MaskColor, this.m_MaskColor);
                e.Graphics.DrawImage(bmp, rect, 0, 0, m_Image.Width, m_Image.Height, GraphicsUnit.Pixel, attr);
            }
        }

        protected override void OnResize(EventArgs eventargs)
        {
            if (Parent == null)
                return;
            Rectangle rc = new Rectangle(this.Location, this.Size);
            Parent.Invalidate(rc, true);
        }
        #endregion

        #region Internal functions
        private void OnFrameChanged(object sender, EventArgs e)
        {
            this.Invalidate();
        }
        #endregion
    }
}
