using System;
using System.Drawing;
using ChaKi.Entity.Search;

namespace ChaKi.GUICommon
{
    internal class LinkArrow
    {
        public int From { get; set; }
        public int To { get; set; }
        public string Text { get; set; }
        public bool Selected { get; set; }
        public LinkCondition Link { get; set; }

        private Point m_Start;
        private Point m_End;
        private Point[] m_Points; // 折線の通過点
        private RectangleF m_TextRect;


        private static Pen m_Pen;
        private static Font m_Font;

        static LinkArrow()
        {
            m_Pen = new Pen(Color.Gray, 1.5F);
            m_Pen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

            m_Font = new Font("Arial", 8F);
        }

        public LinkArrow()
        {
            this.Text = "*";
            m_Points = new Point[4];
        }

        public LinkArrow(LinkArrow src)
        {
            this.From = src.From;
            this.To = src.To;
            this.Text = string.Copy(src.Text);
            this.Selected = src.Selected;
        }

        public void SetPosition(Point start, Point end)
        {
            m_Start = start;
            m_End = end;
        }

        public void SetStart(int x, int y)
        {
            m_Start = new Point(x, y);
            m_End = m_Start;
        }

        public void SetNewEnd(int x)
        {
            m_End.X = x;
        }

        public void Draw(Graphics g, int level, bool drawText)
        {
            int y = Math.Max(m_Start.Y, m_End.Y);
            m_Points[0] = new Point(m_Start.X + level * 4, m_Start.Y);
            m_Points[1] = new Point(m_Start.X + level * 4, y + (level + 1) * 10 + 10);
            m_Points[2] = new Point(m_End.X + level * 4, y + (level + 1) * 10 + 10);
            m_Points[3] = new Point(m_End.X + level * 4, m_End.Y);

            g.DrawLines(m_Pen, m_Points);

            if (drawText)
            {
                SizeF sz = g.MeasureString(this.Text, m_Font);
                PointF mp = new PointF((m_Points[1].X + m_Points[2].X) / 2F, (m_Points[1].Y + m_Points[2].Y) / 2F);
                mp.X -= (sz.Width / 2F);
                g.DrawString(this.Text, m_Font, Brushes.DarkGreen, mp);
                m_TextRect = new RectangleF(mp, sz);
            }
        }

        public LinkArrowHitType HitTest(Point p)
        {
            if (m_TextRect.Contains((float)p.X, (float)p.Y))
            {
                return LinkArrowHitType.AtText;
            }
            int x1 = Math.Min(m_Points[0].X, m_Points[3].X);
            int x2 = Math.Max(m_Points[0].X, m_Points[3].X);
            int y = m_Points[1].Y;
            if (p.X >= x1 && p.X <= x2 && p.Y > y - 4 && p.Y < y + 4)
            {
                return LinkArrowHitType.AtArrow;
            }

            return LinkArrowHitType.None;
        }


    }
}
