using MainShell.Common;
using System;
using System.Collections.Generic;
using System.Windows;

namespace MainShell.Resources.CustomControl
{
    /// <summary>
    /// 芯片Map的数据模型，用于MVVM绑定
    /// </summary>
    public class DieMapModel
    {
        public int Rows { get; private set; }
        public int Columns { get; private set; }
        public Point[,] Coordinates { get; private set; }
        public DieState[,] States { get; private set; }

        public event EventHandler MapInitialized;
        public event EventHandler<(int Row, int Col, DieState State)> DieStateChanged;
        public event EventHandler<IEnumerable<(int Row, int Col, DieState State)>> DieStatesChanged;

        /// <summary>
        /// 初始化Map图大小和坐标
        /// </summary>
        public void Initialize(int rows, int columns, Point[,] coordinates = null)
        {
            Rows = rows;
            Columns = columns;
            Coordinates = coordinates;
            States = new DieState[rows, columns];
            
            // 默认全部设置为NotExist，或者根据需要设置
            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < columns; c++)
                {
                    States[r, c] = DieState.Available;
                }
            }

            MapInitialized?.Invoke(this, EventArgs.Empty);
        }

        /// <summary>
        /// 更新单个芯片状态
        /// </summary>
        public void SetDieState(int row, int col, DieState state)
        {
            if (States != null && row >= 0 && row < Rows && col >= 0 && col < Columns)
            {
                if (States[row, col] != state)
                {
                    States[row, col] = state;
                    DieStateChanged?.Invoke(this, (row, col, state));
                }
            }
        }

        /// <summary>
        /// 批量更新芯片状态
        /// </summary>
        public void SetDieStates(IEnumerable<(int row, int col, DieState state)> updates)
        {
            if (States == null) return;

            bool changed = false;
            foreach (var update in updates)
            {
                if (update.row >= 0 && update.row < Rows && update.col >= 0 && update.col < Columns)
                {
                    if (States[update.row, update.col] != update.state)
                    {
                        States[update.row, update.col] = update.state;
                        changed = true;
                    }
                }
            }

            if (changed)
            {
                DieStatesChanged?.Invoke(this, updates);
            }
        }
    }
}