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.Drawing2D;

namespace vmsnet.HMI
{    
        public partial class BarCtrl : UserControl
        {
            CGROUP NowGrp = null;
            RectangleF BarRect = new RectangleF(0, 0, 0, 0);

            public Boolean Show_DebugMsg { get; set; }

            public BarCtrl()
            {
                InitializeComponent();

                // Initialize Variables

                // Set Optimized Double Buffer to reduce flickering
                this.SetStyle(ControlStyles.UserPaint, true);
                this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

                // Redraw when resized
                this.SetStyle(ControlStyles.ResizeRedraw, true);
                this.Font = SystemInformation.MenuFont;
                Show_DebugMsg = false;
            }

            public CGROUP Group
            {
                set
                {
                    NowGrp = value;
                }
            }
            
            /// Override OnPaint method
            protected override void OnPaint(PaintEventArgs e)
            {
                base.OnPaint(e);
                this.SuspendLayout();

                // AntiAliasing
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                if (bMakeBarRect) MakeBarRect();

                DrawBarGraph(e.Graphics);
                Draw_Debug(e.Graphics);
             
                this.Update();
                this.ResumeLayout();
            }

            public void Draw_Debug(Graphics g)
            {
                if (!Show_DebugMsg) return;

                //Single newy = 50;
                //String newstr = "";
                SizeF fontsize;

                StringBuilder DebugMsg = new StringBuilder();

                
                DebugMsg.AppendLine("GRP=" + this.NowGrp.ToString());
                
          
                // newstr = "CHinfo=" + chinfo.GetUpperBound(0);

                foreach ( CITEM item in NowGrp.Items)
                {
                    DebugMsg.AppendLine("item=" + item.ToString());
                }

                fontsize = g.MeasureString(DebugMsg.ToString(), this.Font);
                g.FillRectangle(new SolidBrush(Color.FromArgb(150, Color.Black)), new Rectangle(0, 0, (int)(fontsize.Width * 1.3), (int)(fontsize.Height * 1.3)));
                g.DrawString(DebugMsg.ToString(), this.Font, Brushes.Tomato, 10, 10);
            }

            protected override void OnSizeChanged(EventArgs e)
            {   
                base.OnSizeChanged(e);
                BarRect = new RectangleF(DisplayRectangle.Left + Padding.Left, DisplayRectangle.Top + Padding.Top, DisplayRectangle.Width - Padding.Left - Padding.Right, DisplayRectangle.Height - Padding.Top - Padding.Bottom);
            }

            public Boolean bMakeBarRect = true;
            private void MakeBarRect()
            {
                if (BarRect.Width == 0) return;
                if (!bMakeBarRect) return;
                if (NowGrp == null) return;
                if (NowGrp.Items == null) return;


                //각아이템의 2pixel 만큼 떨어져있다.
                int ItemWidth = (int)(Math.Floor((this.BarRect.Width - ((NowGrp.NullBalanceSeq - 1) * 1)) / NowGrp.NullBalanceSeq));
                if (ItemWidth < 2) ItemWidth = 2;  //너무작은건 어절수없음
                int ItemHeight = (int)(Math.Floor((BarRect.Height - 20 - 10) / 2));

                int totalWidth = ItemWidth * NowGrp.NullBalanceSeq + ItemWidth;  //1개를 더 추가한다.
                Single CenterMarginX = (BarRect.Width - totalWidth) / 2;

                //차트내의 아이템의 표시영역을 결정
                //UInt16 itemindex = 0;
                foreach (CITEM item in NowGrp.Items)
                {
                    //Single Term = 0;//= item.idx == 0 ? 0 : item.idx * 2;
                    Single X = 0;//(item.idx * ItemWidth) + Term;
                    Single y = 0;//ChartRect.Top;

                    if (item.seq <= NowGrp.NullBalanceSeq)
                    {
                        //상위그룹    
                       // Term = item.seq == 1 ? 0 : (item.seq) * 2;
                        X = (item.seq  * ItemWidth) ;//+ Term;
                        y = 20;
                    }
                    else
                    {
                        //하위그룹
                      //  Term = item.seq == NowGrp.NullBalanceSeq ? 0 : (item.seq - (NowGrp.NullBalanceSeq + 1)) * 2;
                        X = (item.seq - NowGrp.NullBalanceSeq -1) * ItemWidth;//+ Term;
                        y = ItemHeight + 20;
                    }
                    item.BarRect = new RectangleF(BarRect.Left + X + CenterMarginX, BarRect.Top + y, ItemWidth, ItemHeight - 10);
                   // itemindex += 1;
                }
                bMakeBarRect = false;
            }

            private void DrawBarGraph(Graphics g)
            {
                if (BarRect.Width < 1) return;
                if (bMakeBarRect) MakeBarRect();//영역을 새로 생성해야한다면 만듬
                if (NowGrp == null) return;
                if (NowGrp.Items == null) return;


                int YMax = 4;
                int YMin = 0;
                

                ///현재등록된 아이템을 화면에 표시한다.
                foreach (CITEM item in NowGrp.Items)
                {
                    //값에따른 색상입히기
                    Color BarColor = Color.Green;
                    if (item.ismin) BarColor = Color.DeepSkyBlue;
                    else if (item.ismax) BarColor = Color.Tomato;
                    else if (item.onalamh ) BarColor = Color.Red;
                    else if (item.onalaml) BarColor = Color.Blue;  

                    Single Percent = (100 * item.CurValue) / (YMax - YMin);

                    //값에따른 높이값
                    Single ValueHeight = item.BarRect.Height * (Percent / 100);
                    if (ValueHeight > 1)
                    {
                        Single ValueY = item.BarRect.Top + (item.BarRect.Height - ValueHeight);

                        //색상으로 칠한다.
                        g.FillRectangle(new SolidBrush(BarColor), item.BarRect.Left, ValueY, item.BarRect.Width, ValueHeight);

                    }

                    //테두리표시
                    if (item.사용 )
                    {
                        g.DrawRectangle(Pens.Black, item.BarRect.Left, item.BarRect.Top, item.BarRect.Width, item.BarRect.Height);
                    }
                    //g.DrawString(item.idx.ToString("000"), new Font("Arial", 7), Brushes.Black, item.BarRect.Left, item.BarRect.Bottom);
                }
            }

            protected override void OnResize(EventArgs e)
            {
                base.OnResize(e);
                bMakeBarRect = true;
                Invalidate();                
            }

            
            private void InitializeComponent()
            {
                this.SuspendLayout();
                // 
                // DispCtrl
                // 
                this.Name = "BarCtrl";
                this.Size = new System.Drawing.Size(287, 321);                
                this.ResumeLayout(false);
            }


        }       //end class

}   //end namespace