﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using zComp.Core;
using System.Windows.Controls.Primitives;
using System;

namespace zComp.Wpf
{
    /// <summary>Elément utilisé pour le regroupement d'éléments enfants (groupe de boutons radio, ...)</summary>
    public class zRadioGroupBorder : Border
    {
        /// <summary>Constructeur</summary>
        public zRadioGroupBorder()
            : base()
        {
        }

        /// <summary>Permet le regroupement de plusieurs zRadioButtons</summary>
        public static readonly DependencyProperty GroupValueProperty =
            DependencyProperty.Register("GroupValue", typeof(object), typeof(zRadioGroupBorder),
            new PropertyMetadata(null, new PropertyChangedCallback(OnGroupValuePropertyChanged)));

        /// <summary>Permet le regroupement de plusieurs zRadioButtons</summary>
        /// <param name="d">zRadioGroupBorder concerné</param>
        /// <param name="e">Arguments</param>
        private static void OnGroupValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != e.OldValue)
                ((zRadioGroupBorder)d).SetGroupValue(e.NewValue);
        }

        /// <summary>Est-on en train d'assigner le groupe ?</summary>
        private bool settingGroupValue = false;

        /// <summary>Permet le regroupement de plusieurs zRadioButtons</summary>
        /// <param name="value">valeur</param>
        private void SetGroupValue(object value)
        {
            if (!settingGroupValue)
            {
                settingGroupValue = true;
                try
                {
                    foreach (zRadioButton rb in zComp.Wpf.Helpers.WpfHelper.FindChilds<zRadioButton>(this))
                        if (rb.GroupValue != null && rb.GroupValue.Equals(value))
                            rb.IsChecked = true;
                }
                finally
                {
                    settingGroupValue = false;
                }
            }
        }

        /// <summary>Permet le regroupement de plusieurs zRadioButtons</summary>
        public object GroupValue
        {
            get
            {
                return GetValue(GroupValueProperty);
            }
            set
            {
                SetValue(GroupValueProperty, value);
            }
        }
    }
}
