// RadRibbonToggleButtonEx.cs
// Copyright (c) 2016 Bentley Systems, Incorporated. All Rights Reserved.

using System;
using System.Collections.Generic;
using System.Windows;
using Telerik.Windows.Controls;

namespace Haestad.Framework.UI.Integration
{
    /// <summary>
    /// A RadRibbonToggleButton that knows how to synchronize itself with other buttons linked to the same IRibbonUICommand.
    /// If used with a ToggleButtonRibbonUICommand knows how to synchronize other toggle commands in a toggle group.
    /// </summary>
    public class RadRibbonToggleButtonEx : RadRibbonToggleButton, IRibbonLinkedUIElement
    {
        // Note: <whar> An event that can be handled in lieu of click. This is because we suppress the actual Click event 
        // when buttons are in a toggle group and we don't want to allow a second click on a button to toggle it off.
        internal event RoutedEventHandler InternalClick;

        #region Constructor
        public RadRibbonToggleButtonEx()
        {
        }
        #endregion

        #region IRibbonLinkedUIElement Members
        public IRibbonUICommand LinkedRibbonUICommand
        {
            get
            {
                return Command as IRibbonUICommand;
            }
        }
        #endregion

        #region Protected Override Methods
        protected override void OnClick()
        {
            if (InternalClick != null)
                InternalClick.Invoke(this, new RoutedEventArgs());

            if (GetShouldPreventClick())
            {
                Command.Execute(null);
                return;
            }

            base.OnClick();
        }
        #endregion

        #region Private Methods
        private bool GetShouldPreventClick()
        {
            if (GetThisButtonIsInAFunctionalToggleGroup())
                return true;

            return false;
        }

        private bool GetThisButtonIsInAFunctionalToggleGroup()
        {
            if (LinkedRibbonUICommand == null)
                return false;

            if (!(LinkedRibbonUICommand is ToggleButtonRibbonUICommand))
                return false;

            if (!((ToggleButtonRibbonUICommand)LinkedRibbonUICommand).GetIsAtLeastOneOtherToggleButtonInToggleButtonGroup())
                return false;

            return true;
        }
        #endregion
    }
}
