using System;
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Desktop;
///
/// One row of the Plates tab list, as the WinForms list draws it: the plate's number ("New
/// plate" for the trailing empty plate), its size, part count ("Empty" for the new plate),
/// utilization once it holds parts, and how many sheets are cut from it when more than one.
///
public sealed record PlateListRow(string Name, string Size, string Parts, string Utilization, string Quantity)
{
/// The row of the plate at among .
public static PlateListRow For(IList plates, int index)
{
ArgumentNullException.ThrowIfNull(plates);
var plate = plates[index];
var isNewPlate = IsNewPlate(plates, index);
var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff);
return new PlateListRow(
isNewPlate ? "New plate" : $"Plate {index + 1}",
plate.Size.ToString(4),
isNewPlate ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}",
partCount > 0 ? $"{plate.Utilization():P0} utilized" : "",
plate.Quantity > 1 ? $"×{plate.Quantity}" : "");
}
/// Every plate's row, in order.
public static IReadOnlyList For(IList plates)
{
ArgumentNullException.ThrowIfNull(plates);
return Enumerable.Range(0, plates.Count).Select(i => For(plates, i)).ToList();
}
/// The trailing empty plate the list shows as "New plate".
public static bool IsNewPlate(IList plates, int index) =>
index == plates.Count - 1 && plates[index].Parts.Count == 0;
///
/// The gap a plate row dragged in the list is dropped into, 0 (before the first plate)
/// through (after the last movable plate): before the row
/// under the pointer when in its upper half, after it otherwise. The new-plate row and below
/// ( -1) drop after the last plate.
///
public static int DropSlot(int rowIndex, bool upperHalf, int movableCount)
{
if (rowIndex < 0)
return movableCount;
var slot = upperHalf ? rowIndex : rowIndex + 1;
return System.Math.Min(slot, movableCount);
}
/// The index a plate dragged from lands at when dropped in .
public static int DropTarget(int from, int slot) => slot > from ? slot - 1 : slot;
}