using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.Data.SQLite;
using 发电厂.SocketManagement;
using System.Threading.Tasks;
namespace 发电厂
{
    public enum ActionType
    {
        None,
        AddSwitch,
        AddBus,
        AddThreePhaseTransformer,
        AddTwoPhaseTransformer,
        AddGenerator,
        Move,
        MoveAll,
        Rotate,
        ResizeUp,
        ResizeDown,
        ResizeAllUp,
        ResizeAllDown,
        Delete,
        Connect,
        Disconnect,
        GetInfo,
        Open_Close_Switch
    }

    public partial class Form1 : Form
    {
        internal List<Element> elements;
        internal List<(Node, Node)> Connections;
        private ActionType currentAction;
        private Element selectedElement;
        private PointF lastMousePosition;
        private bool isMovingAll;
        private SaveAndLoad saveAndLoad;
        private ConnectionManager connectionManager;
        private UpdateStatus updateStatus;
        private Information information;
        private Transfer transfer;
        public Form1()
        {
            InitializeComponent();
            elements = new List<Element>();
            Connections = new List<(Node, Node)>();
            currentAction = ActionType.None;
            saveAndLoad = new SaveAndLoad(elements, Connections);
            connectionManager = new ConnectionManager(elements, Connections);
            updateStatus = new UpdateStatus(elements, Connections);
            information = new Information(elements);
            transfer = new Transfer(elements);
            this.MouseDown += new MouseEventHandler(Form1_MouseDown);
            this.MouseMove += new MouseEventHandler(Form1_MouseMove);
            this.MouseUp += new MouseEventHandler(Form1_MouseUp);
        }
        
        private void 开关ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.AddSwitch;
            label2.Text = "添加开关";
        }

        private void 母线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.AddBus;
            label2.Text = "添加母线";
        }

        private void 两相变压器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.AddTwoPhaseTransformer;
            label2.Text = "添加两相变压器";
        }

        private void 三相变压器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.AddThreePhaseTransformer;
            label2.Text = "添加三相变压器";
        }

        private void 发电机ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.AddGenerator;
            label2.Text = "添加发电机";
        }

        private void 旋转ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Rotate;
            label2.Text = "旋转";
        }

        private void 平移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Move;
            label2.Text = "平移";
        }

        private void 放大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.ResizeUp;
            label2.Text = "放大";
        }

        private void 缩小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.ResizeDown;
            label2.Text = "缩小";
        }

        private void 整体放大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.ResizeAllUp;
            label2.Text = "整体放大";
        }

        private void 整体缩小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.ResizeAllDown;
            label2.Text = "整体缩小";
        }

        private void 整体平移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.MoveAll;
            label2.Text = "整体平移";
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Delete;
            label2.Text = "删除元件";
        }

        private void 删除所有ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            elements.Clear();
            Connections.Clear();
            updateStatus.UpdatePowerStatus();
            this.Invalidate();
            label2.Text = "删除所有";
        }

        private void 添加连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Connect;
            label2.Text = "添加连接";
        }

        private void 删除连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Disconnect;
            label2.Text = "删除连接";
        }

        private void 开闭开关ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.Open_Close_Switch;
            label2.Text = "开闭开关";
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
                saveFileDialog.Title = "Save Elements as Text File";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    saveAndLoad.SaveElements(saveFileDialog.FileName);
                }
            }
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog.Title = "Open Elements Text File";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    saveAndLoad.LoadElements(openFileDialog.FileName);
                    this.Invalidate(); // 重绘窗体
                }
            }
        }

        private void 导出为图片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PNG Files (*.png)|*.png";
            if(saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                saveAndLoad.ExportToImage(this.ClientSize.Width, this.ClientSize.Height, saveFileDialog.FileName);
            }
        }

        private void 查看信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentAction = ActionType.GetInfo;
            label2.Text = "查看信息";
        }
                
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            PointF clickPoint = new PointF(e.X, e.Y);
            switch(currentAction)
            {
                case ActionType.AddSwitch:
                    elements.Add(new Switch(e.X, e.Y, 30f, 20f, 20f, 2.5f));
                    break;

                case ActionType.AddBus:
                    elements.Add(new Bus(e.X, e.Y, 2f, 50f));
                    break;

                case ActionType.AddTwoPhaseTransformer:
                    elements.Add(new TwoPhaseTransformer(e.X, e.Y, 20f, 20f));
                    break;

                case ActionType.AddThreePhaseTransformer:
                    elements.Add(new ThreePhaseTransformer(e.X, e.Y, 20f, 20f));
                    break;

                case ActionType.AddGenerator:
                    elements.Add(new Generator(e.X, e.Y, 20f, 30f));
                    break;

                case ActionType.ResizeUp:
                    transfer.ResizeElement(clickPoint, 1.2f);
                    break;

                case ActionType.ResizeDown:
                    transfer.ResizeElement(clickPoint, 0.8f);
                    break;

                case ActionType.ResizeAllUp:
                    transfer.ResizeAllElements(1.2f);
                    break;

                case ActionType.ResizeAllDown:
                    transfer.ResizeAllElements(0.8f);
                    break;

                case ActionType.Rotate:
                    transfer.RotateElement(clickPoint); 
                    break;

                case ActionType.Delete:
                    DeleteElement(clickPoint);
                    break;

                case ActionType.Connect:
                    connectionManager.ConnectElements(clickPoint);
                    break;

                case ActionType.Disconnect:
                    connectionManager.DisconnectElements(clickPoint);
                    this.Invalidate(); // 重绘窗体
                    break;

                case ActionType.GetInfo:
                    information.ShowElementInfo(clickPoint);
                    break;

                case ActionType.Open_Close_Switch:
                    foreach(var element in elements)
                    {
                        if(element is Switch sw && sw.Contains(clickPoint))
                        {
                            sw.IsOpen = !sw.IsOpen; // 切换开关的状态
                            updateStatus.UpdatePowerStatus(); // 更新通电状态
                            break;
                        }
                    }
                    break;
            }
            this.Invalidate();
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            lastMousePosition = new PointF(e.X, e.Y);

            // 调用 Transfer 类处理平移操作
            transfer.Form1_MouseDown(new PointF(e.X, e.Y), ref selectedElement, ref isMovingAll, currentAction);
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if(currentAction == ActionType.Move || currentAction == ActionType.MoveAll)
            {
                // 调用 Transfer 类执行平移操作
                transfer.Form1_MouseMove(new PointF(e.X, e.Y), ref selectedElement, ref isMovingAll);
                this.Invalidate(); // 更新窗体
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            // 调用 Transfer 类结束平移操作
            transfer.Form1_MouseUp(ref selectedElement, ref isMovingAll);
        }

        private void DeleteElement(PointF clickPoint)
        {
            for(int i = elements.Count - 1; i >= 0; i--)
            {
                if(elements[i].Contains(clickPoint))
                {
                    Element elementToDelete = elements[i];

                    // 删除与该元件相关的所有节点连接
                    Connections.RemoveAll(connection =>
                        elementToDelete.Nodes.Contains(connection.Item1) || elementToDelete.Nodes.Contains(connection.Item2));

                    // 删除元件
                    elements.RemoveAt(i);

                    // 更新整个电路状态
                    updateStatus.UpdatePowerStatus(); // 在删除元件后调用
                    break;
                }
            }
        }
           
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;

            // 绘制节点间的连接
            foreach(var connection in Connections)
            {
                var node1 = connection.Item1;
                var node2 = connection.Item2;

                // 连接线只有在两个节点都开启且通电时才使用红色
                Pen pen = (node1.IsPowered && node2.IsPowered)
                          ? new Pen(Color.Red, 3)
                          : new Pen(Color.Black, 3);

                g.DrawLine(pen, node1.X, node1.Y, node2.X, node2.Y);
            }

            // 绘制元件
            foreach(var element in elements)
            {
                element.Draw(g);
            }
        }

        private void socketToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerForm socketForm = new ServerForm();
            ClientForm clientForm = new ClientForm(this);
            socketForm.Show();
            clientForm.Show();
        }
    }
}
