using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
///
/// Up to three belts come in, from the left, the right and the back, and one goes out of the front. They take turns, and a
/// side with nothing waiting doesn't hold up the others. E gives one of the three the right of way.
///
public class BeltMerger : Conveyor, IJunction
{
const float Wait = 0.1f;
int _last = -1;
readonly float[] _tried = { -9f, -9f, -9f };
public int ModeCount => 4;
public string ModeName(int mode) => mode == 0 ? Loc.T("the belts take turns") : mode == 1 ? Loc.T("the left belt goes first") : mode == 2 ? Loc.T("the right belt goes first") : Loc.T("the back belt goes first");
public Color ModeColor(int mode) => mode == 0 ? Color.white : new Color(0.3f, 0.6f, 0.95f);
// route 0 = in from the left, route 1 = in from the right, route 2 = in from the back
protected override int RouteCount => 3;
static float Side(int route) => route == 0 ? -1f : route == 1 ? 1f : 0f;
protected override Vector2 PathAt(float d, int route) =>
d < 0.5f && route != 2 ? new Vector2(Side(route) * (0.5f - d), 0f) : new Vector2(0f, d - 0.5f);
public override void Ports(List into)
{
for (int r = 0; r < 3; r++)
into.Add(new Port { at = WorldOnPath(0f, r, 0f), dir = r == 2 ? transform.forward : transform.right * -Side(r), input = true });
into.Add(new Port { at = WorldOnPath(1f, 0, 0f), dir = transform.forward });
}
protected override bool Takes(int port)
{
_tried[port] = Time.time;
int first = Mode - 1;
if (first >= 0) return port == first || Time.time - _tried[first] > Wait;
for (int k = 1; k <= 3; k++)
{
int other = (_last + 3 + k) % 3;
if (other == port) return true;
if (Time.time - _tried[other] < Wait) return false;
}
return true;
}
protected override int EntryRoute(Cargo c, int port)
{
_last = port;
Sfx.PlayAt("merger_clunk", transform.position + transform.up * 0.4f, 0.35f, 1f, 0.08f, 0.25f);
return port;
}
protected override int RouteAt(Vector2 local, Cargo c) => local.x < -0.1f ? 0 : local.x > 0.1f ? 1 : 2;
}
}