using CanFly.Canvas.Shape;
using CanFly.Helper;
using CanFly.UI;
using CanFly.UI.GuidePanel;
using CanFly.Util;
using HalconDotNet;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace CanFly
{
    public partial class FrmMain : Form
    {

        private string _currentImageFile = "";
        private System.Windows.Forms.Timer _statusTimer = new System.Windows.Forms.Timer();
        private BaseGuideControl? _currentGuideCtrl;


        public FrmMain()
        {
            InitializeComponent();
            this.canvas.mouseMoved += Canvas_mouseMoved;
            this.canvas.OnShapeUpdateEvent += Canvas_OnShapeUpdateEvent;
            this.canvas.selectionChanged += Canvas_selectionChanged;

            this.canvas.OnShapeMoving += Canvas_OnShapeMoving;
        }



        private void FrmMain_Load(object sender, EventArgs e)
        {
            _currentImageFile = @"C:\Users\DEV\Desktop\ÂÝË¿\Cam7_130252457.jpg";
            Bitmap bitmap = (Bitmap)Image.FromFile(_currentImageFile);
            this.canvas.LoadPixmap(bitmap);
            this.btnCreateCircle.Enabled = true;
            this.canvas.Enabled = true;
        }


        private void btnLoadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "ͼÏñÎļþ|*.jpg;*.png";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                _currentImageFile = ofd.FileName;
                //this.canvasMain.LoadImageFile(_currentImageFile); 
                Bitmap bitmap = (Bitmap)Image.FromFile(_currentImageFile);
                this.canvas.LoadPixmap(bitmap);
                this.btnCreateCircle.Enabled = true;
            }
        }


        private void btnCreateCircle_Click(object sender, EventArgs e)
        {
            //FrmGuideCircle frmGuideCircle = new FrmGuideCircle();
            //panelGuide.ShowForm(frmGuideCircle);

            SwitchGuideForm(ShapeTypeEnum.Circle);
            this.canvas.StartDraw(ShapeTypeEnum.Circle);

            this.btnCreateCircle.Enabled = false;
            this.btnStopDraw.Enabled = true;
            this.canvas.Enabled = true;
        }



        private void btnCreateRect_Click(object sender, EventArgs e)
        {
            this.canvas.StartDraw(ShapeTypeEnum.Rectangle);

            this.btnCreateCircle.Enabled = false;
            this.btnStopDraw.Enabled = true;
            this.canvas.Enabled = true;
        }



        private void btnStopDraw_Click(object sender, EventArgs e)
        {
            //panelGuide.Controls.Clear();
            StopDrawMode();
        }



        private void StartDrawMode()
        {

        }


        private void StopDrawMode()
        {
            this.canvas.StopDraw();


            this.btnStopDraw.Enabled = false;
            this.btnCreateCircle.Enabled = true;
        }





        private void Status(string message, int delay = 5000)
        {
            _statusTimer.Stop();
            // ÏÔʾÏûÏ¢
            lblStatus.Text = message;

            // ´´½¨Ò»¸ö¼ÆʱÆ÷

            _statusTimer.Interval = delay; // ÉèÖÃÑÓ³Ùʱ¼ä
            _statusTimer.Tick += (sender, e) =>
            {
                _statusTimer.Stop(); // Í£Ö¹¼ÆʱÆ÷
                lblStatus.Text = string.Empty; // Çå¿Õ״̬ÏûÏ¢
            };
            _statusTimer.Start(); // Æô¶¯¼ÆʱÆ÷
        }




        private void Canvas_mouseMoved(PointF pos)
        {
            if (InvokeRequired)
            {
                Invoke(Canvas_mouseMoved, pos);
                return;
            }

            lblStatus.Text = $"X:{pos.X}, Y:{pos.Y}";

        }




        private void Canvas_selectionChanged(List<FlyShape> shapes)
        {
            if (shapes.Count != 1)
            {
                // panelGuide.Controls.Clear();
                return;
            }
            //SwitchGuideForm(shapes[0].ShapeType);
            Canvas_OnShapeUpdateEvent(shapes[0]);

        }



        private void SwitchGuideForm(ShapeTypeEnum shapeType)
        {
            if (_currentGuideCtrl == null)
            {
                switch (shapeType)
                {
                    case ShapeTypeEnum.Point:
                        break;
                    case ShapeTypeEnum.Line:
                        break;
                    case ShapeTypeEnum.Rectangle:
                        break;
                    case ShapeTypeEnum.Circle:
                        _currentGuideCtrl = new GuideCircleCtrl();
                        _currentGuideCtrl.CurrentImageFile = _currentImageFile;
                     
                        _currentGuideCtrl.OnControlCloseEvent += () =>
                        {
                            panelGuide.Controls.Clear();
                            StopDrawMode();
                        };
                        break;
                    case ShapeTypeEnum.Polygon:
                        break;
                    case ShapeTypeEnum.LineStrip:
                        break;
                    default:
                        break;
                }
            }
            //_currentGuideCtrl?.AddToPanel(panelGuide);
        }



        private void Canvas_OnShapeMoving(List<FlyShape> shapes)
        {
            if (shapes.Count != 1)
            {
                panelGuide.Controls.Clear();
                return;
            }

           // _currentGuideCtrl?.UpdateShape(shapes[0]);
        }



        private void Canvas_OnShapeUpdateEvent(FlyShape shape)
        {
            switch (shape.ShapeType)
            {
                case ShapeTypeEnum.Point:
                    break;
                case ShapeTypeEnum.Line:
                    break;
                case ShapeTypeEnum.Rectangle:
                    break;
                case ShapeTypeEnum.Circle:
                    {
                        //_currentGuideCtrl?.UpdateShape(shape);
                    }
                    break;
                case ShapeTypeEnum.Polygon:
                    break;
                case ShapeTypeEnum.LineStrip:
                    break;
                default:
                    break;
            }
        }



        private void btnTestOutsideDraw_Click(object sender, EventArgs e)
        {
            Random random = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 10; i++)
            {
                // this.canvas.DrawCircle(new PointF(500, 500), 100);

                int x = random.Next() % 500;
                int y = random.Next() % 500;
                int r = random.Next() % 200;

                Debug.WriteLine($"X:{x}\tY:{y}\tR:{r}");

                this.canvas.DrawCircle(new PointF(x, y), r);
            }
        }

        private void btnTestClearDraw_Click(object sender, EventArgs e)
        {
            this.canvas.ClearDraw();
        }



        private async void btnTestCircleMeasure_Click(object sender, EventArgs e)
        {
            //string dir = Path.Combine(Environment.CurrentDirectory, "hscripts");
            //string file = "CircleMeasure.hdvp";
            //string filePath = Path.Combine(dir, file);
            //if (!File.Exists(filePath))
            //{
            //    MessageBox.Show($"Îļþ {filePath} ²»´æÔÚ");
            //    return;
            //}

            //HObject? hImage = null;

            //try
            //{
            //    HDevEngineTool tool = new HDevEngineTool(dir);
            //    tool.LoadProcedure(Path.GetFileNameWithoutExtension(file));

            //    // string imageFile = Path.Combine(Environment.CurrentDirectory, "hscripts", "image.png");

            //    HOperatorSet.ReadImage(out hImage, _currentImageFile);
            //    tool.InputImageDic["INPUT_Image"] = hImage;
            //    tool.InputTupleDic["XCenter"] = 981.625;
            //    tool.InputTupleDic["YCenter"] = 931.823;
            //    tool.InputTupleDic["Radius"] = 900.141;

            //    Stopwatch sw = new Stopwatch();
            //    sw.Start();
            //    if (!tool.RunProcedure(out string error, out _))
            //    {
            //        throw new Exception();
            //    }
            //    sw.Stop();



            //    var flag = tool.GetResultTuple("OUTPUT_Flag").HTupleToDouble();
            //    List<double> x = tool.GetResultTuple("RXCenter").HTupleToDouble();
            //    var y = tool.GetResultTuple("RYCenter").HTupleToDouble();
            //    var r = tool.GetResultTuple("RRadius").HTupleToDouble();

            //    if (flag.Count > 0 && x.Count > 0 && y.Count > 0 && r.Count > 0)
            //    {
            //        this.canvas.DrawCircle(new PointF((float)x[0], (float)y[0]), (float)r[0]);
            //    }

            //    //
            //    Debug.WriteLine("");
            //}
            //catch (Exception)
            //{
            //    throw;
            //}
            //finally
            //{
            //    hImage?.Dispose();
            //}


        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            this.canvas.DrawRectangle(new PointF(300, 300),
                new PointF(800, 500), 33f);
        }


        private void btnRotateTest_Click(object sender, EventArgs e)
        {
            if (this.canvas.Shapes.Count == 0)
            {
                return;
            }
            
            this.canvas.Shapes[0]._currentRotateAngle += 10;

            //var shp = this.canvas.Shapes[this.canvas.Shapes.Count - 1].Copy();
            //shp.Rotate += 10;
            //this.canvas.Shapes.Add(shp);


            this.canvas.Invalidate();
        }
    }
}