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.
internal T GetValueForScreen(int screenId)
{
this.RemoveDeadPlayers();
return this.States.TryGetValue(screenId, out T state)
? state
: this.States[screenId] = this.CreateNewState();
}
/// Set the value for a given screen ID, creating it if needed.
/// The screen ID whose value set.
/// The value to set.
internal void SetValueForScreen(int screenId, T value)
{
this.RemoveDeadPlayers();
this.States[screenId] = value;
}
/*********
** Private methods
*********/
/// Remove players who are no longer have a split-screen index.
/// Returns whether any players were removed.
private void RemoveDeadPlayers()
{
if (this.LastRemovedScreenId == Context.LastRemovedScreenId)
return;
this.LastRemovedScreenId = Context.LastRemovedScreenId;
foreach (int id in this.States.Keys.ToArray())
{
if (!Context.HasScreenId(id))
this.States.Remove(id);
}
}
}
}