using System;
using System.Collections.Generic;
using System.Linq;
namespace StardewModdingAPI.Utilities
{
/// Manages a separate value for each player in split-screen mode. This can safely be used in non-split-screen mode too, it'll just have a single state in that case.
/// The state class.
public class PerScreen
{
/*********
** Fields
*********/
/// Create the initial value for a player.
private readonly Func CreateNewState;
/// The tracked values for each player.
private readonly IDictionary States = new Dictionary();
/// The last value for which this instance was updated.
private int LastRemovedScreenId;
/*********
** Accessors
*********/
/// The value for the current player.
/// The value is initialized the first time it's requested for that player, unless it's set manually first.
public T Value
{
get => this.GetValueForScreen(Context.ScreenId);
set => this.SetValueForScreen(Context.ScreenId, value);
}
/*********
** Public methods
*********/
/// Construct an instance.
public PerScreen()
: this(null) { }
/// Construct an instance.
/// Create the initial state for a player screen.
public PerScreen(Func createNewState)
{
this.CreateNewState = createNewState ?? (() => default);
}
/// Get the value for a given screen ID, creating it if needed.
/// The screen ID to check.
public T GetValueForScreen(int screenId)
{
this.RemoveDeadScreens();
return this.States.TryGetValue(screenId, out T state)
? state
: this.States[screenId] = this.CreateNewState();
}
/// Set the value for a given screen ID.
/// The screen ID whose value set.
/// The value to set.
public void SetValueForScreen(int screenId, T value)
{
this.RemoveDeadScreens();
this.States[screenId] = value;
}
/*********
** Private methods
*********/
/// Remove screens which are no longer active.
private void RemoveDeadScreens()
{
if (this.LastRemovedScreenId == Context.LastRemovedScreenId)
return;
this.LastRemovedScreenId = Context.LastRemovedScreenId;
foreach (var pair in this.States.ToArray())
{
if (!Context.HasScreenId(pair.Key))
this.States.Remove(pair.Key);
}
}
}
}