using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
///
/// A piece of the power network: a panel, a battery or a pole. Nodes join up with whatever lies inside the longer of
/// their radii, machines with any node that reaches them, and everything joined shares one supply.
///
public abstract class PowerNode : NetworkBehaviour, IInteractable
{
public static readonly List All = new List();
/// What the whole network this node is on is doing, in kilowatts and kilowatt-hours.
public readonly NetworkVariable Supply = new NetworkVariable();
public readonly NetworkVariable Asked = new NetworkVariable();
public readonly NetworkVariable Held = new NetworkVariable();
public readonly NetworkVariable Cap = new NetworkVariable();
BuildPiece _piece;
protected BuildPiece Piece => _piece ? _piece : (_piece = GetComponent());
public abstract float Radius { get; }
/// Where a wire ties on.
public virtual float WireHeight => 1.6f;
/// Kilowatts the sun gives it right now.
public virtual float Sunlight => 0f;
public abstract string Prompt { get; }
public bool CanInteract => false;
public void Interact() { }
/// The network in a few words, for the prompt.
protected string Network
{
get
{
bool batteries = Cap.Value > 0f;
if (Asked.Value <= 0f)
return batteries ? Loc.F("nothing to run, {0:0.#} kW free, batteries {1:0.0} of {2:0} kWh", Supply.Value, Held.Value, Cap.Value) : Loc.F("nothing to run, {0:0.#} kW free", Supply.Value);
float at = Mathf.Clamp01(Supply.Value / Asked.Value) * 100f;
return batteries ? Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW, batteries {3:0.0} of {4:0} kWh", at, Supply.Value, Asked.Value, Held.Value, Cap.Value) : Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW", at, Supply.Value, Asked.Value);
}
}
public override void OnNetworkSpawn() => All.Add(this);
public override void OnNetworkDespawn() => All.Remove(this);
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
public void Report(float supply, float asked, float held, float cap)
{
Write(Supply, supply);
Write(Asked, asked);
Write(Held, held);
Write(Cap, cap);
}
protected static void Write(NetworkVariable v, float value)
{
if (Mathf.Abs(v.Value - value) > 0.01f || (value == 0f && v.Value != 0f)) v.Value = value;
}
}
}