using System;
using System.Collections.Generic;
using MySqlConnector;
using CncSimulator.Config;

namespace CncSimulator.Core
{
    /// <summary>
    /// 数据库读取器。从MariaDB读取采集地址和机床信息。
    /// </summary>
    public class DatabaseReader
    {
        private readonly string _connectionString;

        public DatabaseReader(string connectionString)
        {
            _connectionString = connectionString;
        }

        /// <summary>测试数据库连接</summary>
        public bool TestConnection(out string error)
        {
            error = "";
            try
            {
                using (var conn = new MySqlConnection(_connectionString))
                {
                    conn.Open();
                    return true;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }

        /// <summary>读取所有采集地址及其机床</summary>
        public List<AddressInfo> ReadAddresses()
        {
            var addresses = new List<AddressInfo>();

            using (var conn = new MySqlConnection(_connectionString))
            {
                conn.Open();

                // 读取采集地址
                string addrSql = "SELECT id, name, url FROM cnc_collect_address ORDER BY id";
                using (var cmd = new MySqlCommand(addrSql, conn))
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        addresses.Add(new AddressInfo
                        {
                            DbId = reader.GetInt32("id"),
                            Name = reader.GetString("name"),
                            Url = reader.IsDBNull(reader.GetOrdinal("url")) ? "" : reader.GetString("url"),
                            Machines = new List<MachineInfo>()
                        });
                    }
                }

                // 为每个地址读取机床
                foreach (var addr in addresses)
                {
                    string machineSql = "SELECT id, device_code, name FROM cnc_machine WHERE collect_address_id = @addrId ORDER BY id";
                    using (var cmd = new MySqlCommand(machineSql, conn))
                    {
                        cmd.Parameters.AddWithValue("@addrId", addr.DbId);
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                addr.Machines.Add(new MachineInfo
                                {
                                    Id = reader.GetInt32("id"),
                                    DeviceCode = reader.GetString("device_code"),
                                    Name = reader.IsDBNull(reader.GetOrdinal("name")) ? "" : reader.GetString("name")
                                });
                            }
                        }
                    }
                }
            }

            return addresses;
        }
    }

    /// <summary>采集地址信息（从数据库读取）</summary>
    public class AddressInfo
    {
        public int DbId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public List<MachineInfo> Machines { get; set; }
    }

    /// <summary>机床信息（从数据库读取）</summary>
    public class MachineInfo
    {
        public int Id { get; set; }
        public string DeviceCode { get; set; }
        public string Name { get; set; }
    }
}
