using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace 发电厂
{
    public class SaveAndLoad
    {
        private List<Element> elements;
        private List<(Node, Node)> Connections;
        // 构造函数，传入元素和连接列表
        public SaveAndLoad(List<Element> elements, List<(Node, Node)> Connections)
        {
            this.elements = elements;
            this.Connections = Connections;
        }
        public void SaveElements(string filePath)
        {
            using(StreamWriter writer = new StreamWriter(filePath))
            {
                foreach(var element in elements)
                {
                    // 写入元素的类型
                    writer.WriteLine(element.GetType().Name);

                    // 写入元素的基本属性
                    writer.WriteLine($"{element.X},{element.Y},{element.Angle},{element.TextSize},{element.IsPowered}");

                    // 根据不同类型写入特定属性
                    switch(element)
                    {
                        case Switch sw:
                            writer.WriteLine($"{sw.Width},{sw.Height},{sw.LineLength},{sw.CircleRadius},{sw.IsOpen}");
                            break;
                        case Bus bus:
                            writer.WriteLine($"{bus.Width},{bus.Height}");
                            break;
                        case TwoPhaseTransformer twoPhaseTransformer:
                            writer.WriteLine($"{twoPhaseTransformer.Radius},{twoPhaseTransformer.Length}");
                            break;
                        case ThreePhaseTransformer threePhaseTransformer:
                            writer.WriteLine($"{threePhaseTransformer.Radius},{threePhaseTransformer.Length}");
                            break;
                        case Generator generator:
                            writer.WriteLine($"{generator.Radius},{generator.Length}");
                            break;
                    }

                    // 写入节点信息
                    writer.WriteLine(element.Nodes.Count);
                    foreach(var node in element.Nodes)
                    {
                        writer.WriteLine($"{node.X},{node.Y},{node.NodeRadius},{node.IsPowered}");
                    }
                }
                // 写入连接信息
                writer.WriteLine("Connections");
                foreach(var connection in Connections)
                {
                    int index1 = elements.SelectMany(e => e.Nodes).ToList().IndexOf(connection.Item1);
                    int index2 = elements.SelectMany(e => e.Nodes).ToList().IndexOf(connection.Item2);
                    writer.WriteLine($"{index1},{index2}");
                }

            }
        }

        public void LoadElements(string filePath)
        {
            elements.Clear();
            Connections.Clear();
            var allNodes = new List<Node>();
            using(StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while((line = reader.ReadLine()) != null && line != "Connections")
                {
                    Element element = null;
                    string elementType = line;

                    // 读取基本属性
                    string[] basicAttributes = reader.ReadLine().Split(',');
                    float x = float.Parse(basicAttributes[0]);
                    float y = float.Parse(basicAttributes[1]);
                    float angle = float.Parse(basicAttributes[2]);
                    float textSize = float.Parse(basicAttributes[3]);
                    bool isPowered = bool.Parse(basicAttributes[4]);

                    // 根据类型实例化不同元素并读取特定属性
                    switch(elementType)
                    {
                        case "Switch":
                            string[] switchAttributes = reader.ReadLine().Split(',');
                            element = new Switch(x, y, float.Parse(switchAttributes[0]), float.Parse(switchAttributes[1]), float.Parse(switchAttributes[2]), float.Parse(switchAttributes[3]));
                            ((Switch)element).IsOpen = bool.Parse(switchAttributes[4]);
                            break;
                        case "Bus":
                            string[] busAttributes = reader.ReadLine().Split(',');
                            element = new Bus(x, y, float.Parse(busAttributes[0]), float.Parse(busAttributes[1]));
                            break;
                        case "TwoPhaseTransformer":
                            string[] twoPhaseAttributes = reader.ReadLine().Split(',');
                            element = new TwoPhaseTransformer(x, y, float.Parse(twoPhaseAttributes[0]), float.Parse(twoPhaseAttributes[1]));
                            break;
                        case "ThreePhaseTransformer":
                            string[] threePhaseAttributes = reader.ReadLine().Split(',');
                            element = new ThreePhaseTransformer(x, y, float.Parse(threePhaseAttributes[0]), float.Parse(threePhaseAttributes[1]));
                            break;
                        case "Generator":
                            string[] generatorAttributes = reader.ReadLine().Split(',');
                            element = new Generator(x, y, float.Parse(generatorAttributes[0]), float.Parse(generatorAttributes[1]));
                            break;
                    }

                    // 设置通用属性
                    if(element != null)
                    {
                        element.Angle = angle;
                        element.TextSize = textSize;
                        element.IsPowered = isPowered;

                        // 读取节点信息
                        int nodeCount = int.Parse(reader.ReadLine());
                        for(int i = 0; i < nodeCount; i++)
                        {
                            string[] nodeAttributes = reader.ReadLine().Split(',');
                            float nodeX = float.Parse(nodeAttributes[0]);
                            float nodeY = float.Parse(nodeAttributes[1]);
                            float nodeRadius = float.Parse(nodeAttributes[2]);
                            bool nodeIsPowered = bool.Parse(nodeAttributes[3]);

                            var node = new Node(nodeX, nodeY, nodeRadius) { IsPowered = nodeIsPowered };
                            element.Nodes.Add(node);
                            allNodes.Add(node); // 将所有节点添加到列表中，以便稍后使用索引重建连接
                        }
                        elements.Add(element);
                    }
                }
                while((line = reader.ReadLine()) != null)
                {
                    string[] connectionIndices = line.Split(',');
                    int index1 = int.Parse(connectionIndices[0]);
                    int index2 = int.Parse(connectionIndices[1]);
                    if(index1 >= 0 && index2 >= 0 && index1 < allNodes.Count && index2 < allNodes.Count)
                    {
                        Connections.Add((allNodes[index1], allNodes[index2]));
                    }
                }
            }
            //this.Invalidate(); // 重绘窗体
        }


        public void ExportToImage(int width, int height, string fileName)
        {
            Bitmap bitmap = new Bitmap(width, height);
            using(Graphics g = Graphics.FromImage(bitmap))
            {
                // 填充白色背景
                g.Clear(Color.White);

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

            bitmap.Save(fileName);
        }

    }
}
