using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
namespace UIWidgets {
///
/// Works like ToogleGroup for Switches.
/// A Switch Group is not a visible UI control but rather a way to modify the behavior of a set of Switches.
// Switches that belong to the same group are constrained so that only one of them can switched on at a time - pressing one of them to switch it on automatically switches the others off.
///
[AddComponentMenu("UI/UIWidgets/SwitchGroup")]
public class SwitchGroup : MonoBehaviour
{
///
/// Is it allowed that no switch is switched on?
///
[SerializeField]
public bool AllowSwitchOff;
[System.NonSerialized]
protected HashSet Switches = new HashSet();
///
/// Check if switch is in group.
///
/// Current switch.
protected void ValidateSwitchIsInGroup(Switch currentSwitch)
{
if (currentSwitch==null || !Switches.Contains(currentSwitch))
{
throw new ArgumentException(string.Format("Switch {0} is not part of SwitchGroup {1}", currentSwitch, this));
}
}
///
/// Notifies the switch on.
///
/// Current switch.
public void NotifySwitchOn(Switch currentSwitch)
{
ValidateSwitchIsInGroup(currentSwitch);
foreach (var s in Switches)
{
if (s!=currentSwitch)
{
s.IsOn = false;
}
}
}
///
/// Unregisters the switch.
///
/// Current switch.
public void UnregisterSwitch(Switch currentSwitch)
{
Switches.Remove(currentSwitch);
}
///
/// Registers the switch.
///
/// Toggle.
public void RegisterSwitch(Switch toggle)
{
Switches.Add(toggle);
}
///
/// Is any switch on?
///
/// true, if switches on was anyed, false otherwise.
public bool AnySwitchesOn()
{
return Switches.FirstOrDefault(x => x.IsOn) != null;
}
///
/// Get active the switches.
///
/// The switches.
public IEnumerable ActiveSwitches()
{
return Switches.Where(x => x.IsOn);
}
///
/// Sets all switches off.
///
public void SetAllSwitchesOff()
{
bool oldAllowSwitchOff = AllowSwitchOff;
AllowSwitchOff = true;
foreach (var s in Switches)
{
s.IsOn = false;
}
AllowSwitchOff = oldAllowSwitchOff;
}
}
}