// ========================================================================
//
// Copyright (C) 2013-2014 MARC CHEVALDONNE
//                         marc.chevaldonne.free.fr
//
// Module        : MorpionGrid.xaml.cs
// Author        : Marc Chevaldonné
// Creation date : 2014-05-07
//
// ========================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using giMorpionCore;

namespace MorpionGameWpf
{
    /// <summary>
    /// Logique d'interaction pour MorpionGrid.xaml
    /// </summary>
    public partial class MorpionGrid : UserControl
    {
        public MorpionGrid()
        {
            InitializeComponent();
        }



        public Game Game
        {
            get { return (Game)GetValue(GameProperty); }
            set { SetValue(GameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Game.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty GameProperty =
            DependencyProperty.Register("Game", typeof(Game), typeof(MorpionGrid));

        static Dictionary<int, string> mPlayerSymbols = new Dictionary<int, string>() { {-1, " "}, { 0, "O" }, { 1, "X" } };


        public void Update(params Case[] highlightedPlaces)
        {
            if(Game == null)
            {
                return;
            }
            int[,] board = Game.Board;

            if (mGrid.RowDefinitions.Count == 0)
            {
                for (int i = 0; i < board.GetLength(0); i++)
                {
                    mGrid.RowDefinitions.Add(new RowDefinition());
                }
                for (int i = 0; i < board.GetLength(1); i++)
                {
                    mGrid.ColumnDefinitions.Add(new ColumnDefinition());
                }
            }

            mGrid.Children.Clear();

            for (int i = 0; i < board.GetLength(0); i++)
            {
                for (int j = 0; j < board.GetLength(1); j++)
                {
                    var newCase = new MorpionGridCase() { PlayerId = mPlayerSymbols[board[i,j]]};
                    if (highlightedPlaces.Cast<Case>().Contains(new Case(i, j)))
                    {
                        newCase.BackgroundColor = Brushes.Red;
                    }
                    newCase.SetValue(Grid.RowProperty, i);
                    newCase.SetValue(Grid.ColumnProperty, j);
                    mGrid.Children.Add(newCase);
                }
            }
        }
    }
}
