using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OpenNest.CommonLines;
namespace OpenNest.IO
{
///
/// Parts copied from a plate (Edit > Copy or Cut) for pasting into any open nest, the one they
/// came from or another. Each part is cloned as it was copied, with its placed program, lead-ins
/// and the common-line groups among the copied parts; each drawing is kept as the nest file saves
/// it, so editing or closing the source nest afterwards changes nothing here. Cut-off parts are
/// plate definitions, not parts, and are never copied. See docs/copy-paste-parts.md.
///
public sealed class CopiedParts
{
// A .nest archive holding the copied drawings and no plates.
private readonly byte[] drawingsArchive;
private readonly List<(Part Part, string DrawingName)> parts;
// Drawing name -> DrawingPackage.GeometryKey, in order of first use.
private readonly List<(string Name, string GeometryKey)> drawings;
private CopiedParts(byte[] drawingsArchive, List<(Part, string)> parts,
List<(string, string)> drawings, List<(int[] Members, double Kerf)> commonLines, Units units)
{
this.drawingsArchive = drawingsArchive;
this.parts = parts;
this.drawings = drawings;
CommonLines = commonLines;
Units = units;
}
/// The units the copied drawings are drawn in.
public Units Units { get; }
public int Count => parts.Count;
/// The names of the copied parts' drawings, each once, in the order the parts use them.
public IReadOnlyList DrawingNames => drawings.Select(d => d.Name).ToList();
/// The common-line groups among the copied parts, by index into the copy.
public IReadOnlyList<(int[] Members, double Kerf)> CommonLines { get; }
///
/// Copies from of .
/// Cut-off parts are left out; null when nothing else was selected.
///
public static CopiedParts Capture(Nest nest, Plate plate, IEnumerable selected)
{
ArgumentNullException.ThrowIfNull(nest);
ArgumentNullException.ThrowIfNull(selected);
var sources = selected.Where(p => p != null && !p.BaseDrawing.IsCutOff).ToList();
if (sources.Count == 0)
return null;
var byName = new Dictionary(StringComparer.Ordinal);
var order = new List();
foreach (var part in sources)
{
var name = part.BaseDrawing.Name ?? "";
if (!byName.TryGetValue(name, out var known))
{
byName.Add(name, part.BaseDrawing);
order.Add(part.BaseDrawing);
}
else if (!ReferenceEquals(known, part.BaseDrawing))
{
throw new InvalidOperationException($"Two different drawings are named '{name}'.");
}
}
var holder = new Nest(nest.Name) { Units = nest.Units };
foreach (var drawing in order)
holder.Drawings.Add(drawing);
using var stream = new MemoryStream();
new NestWriter(holder).Write(stream);
var keyed = order.Select(d => (d.Name ?? "", GeometryKey(d, nest.Units))).ToList();
var copies = sources.Select(p => ((Part)p.Clone(), p.BaseDrawing.Name ?? "")).ToList();
var commonLines = CommonLineGroup.AmongParts(plate, sources);
return new CopiedParts(stream.ToArray(), copies, keyed, commonLines, nest.Units);
}
///
/// Plans pasting the copy into without changing it. A drawing the
/// nest already has under the same name is used when it is the same drawing (same geometry,
/// whatever its quantities, color or nesting settings); otherwise the paste is refused, since
/// a nest cannot hold two drawings with one name. A drawing the nest lacks is added as an
/// exact copy, with the required quantity it had where it was copied from.
///
public PartsPaste PlanPaste(Nest target)
{
ArgumentNullException.ThrowIfNull(target);
if (target.Units != Units)
return PartsPaste.Refuse(target, $"The copied parts are drawn in {UnitName(Units)} and this nest "
+ $"is in {UnitName(target.Units)}. Converting units is not supported.");
var conflicts = new List();
var map = new Dictionary(StringComparer.Ordinal);
var matched = new List();
var missing = new List();
foreach (var (name, key) in drawings)
{
var existing = target.Drawings.FirstOrDefault(d => string.Equals(d.Name ?? "", name, StringComparison.Ordinal));
if (existing == null)
missing.Add(name);
else if (existing.IsCutOff || GeometryKey(existing, target.Units) != key)
conflicts.Add(name);
else
{
map[name] = existing;
matched.Add(existing);
}
}
if (conflicts.Count > 0)
return PartsPaste.Refuse(target, conflicts.Count == 1
? $"This nest already has a different drawing named '{conflicts[0]}'. Rename one of them first."
: "This nest already has different drawings with these names; rename them first:"
+ Environment.NewLine + string.Join(Environment.NewLine, conflicts.Select(n => "- " + n)));
var added = new List();
if (missing.Count > 0)
{
var copies = new NestReader(new MemoryStream(drawingsArchive, writable: false)).Read().Drawings
.ToDictionary(d => d.Name ?? "", StringComparer.Ordinal);
// The next palette slots, as reopening the nest would give them.
var slot = target.Drawings.Count(d => !d.IsCutOff);
foreach (var name in missing)
{
// Read from an archive with no plates: nothing is nested yet.
var copy = copies[name];
if (!copy.HasCustomColor)
copy.Color = Drawing.GetPartColor(slot);
slot++;
map[name] = copy;
added.Add(copy);
}
}
var placed = parts.Select(p => p.Part.CloneFor(map[p.DrawingName])).ToList();
return new PartsPaste(target, added, matched, placed, CommonLines);
}
private static string GeometryKey(Drawing drawing, Units units) =>
DrawingPackage.GeometryKey(DrawingPackage.Write(drawing, units));
private static string UnitName(Units units) => units.ToString().ToLowerInvariant();
}
///
/// How enter one nest: the drawings to add, the drawings it already
/// has, and the parts bound to them at the positions they were copied from; or a refusal.
///
public sealed class PartsPaste
{
private bool drawingsAdded;
internal PartsPaste(Nest nest, IReadOnlyList added, IReadOnlyList matched,
IReadOnlyList parts, IReadOnlyList<(int[] Members, double Kerf)> commonLines)
{
Nest = nest;
AddedDrawings = added;
MatchedDrawings = matched;
Parts = parts;
CommonLines = commonLines;
Refusal = "";
}
private PartsPaste(Nest nest, string refusal)
{
Nest = nest;
AddedDrawings = Array.Empty();
MatchedDrawings = Array.Empty();
Parts = Array.Empty();
CommonLines = Array.Empty<(int[], double)>();
Refusal = refusal;
}
internal static PartsPaste Refuse(Nest nest, string refusal) => new(nest, refusal);
public Nest Nest { get; }
/// Exact copies of drawings the nest lacks, which adds.
public IReadOnlyList AddedDrawings { get; }
/// The nest's own drawings the copied parts turned out to be.
public IReadOnlyList MatchedDrawings { get; }
/// The copied parts bound to this nest's drawings, where they were copied from; not on any plate.
public IReadOnlyList Parts { get; }
/// The common-line groups among , by index.
public IReadOnlyList<(int[] Members, double Kerf)> CommonLines { get; }
/// Why nothing may be pasted; empty unless .
public string Refusal { get; }
public bool IsRefused => Refusal.Length > 0;
/// Adds to the nest; call before placing any part, once.
public void AddDrawings()
{
if (IsRefused)
throw new InvalidOperationException(Refusal);
if (drawingsAdded)
return;
foreach (var drawing in AddedDrawings)
{
if (!Nest.Drawings.Add(drawing))
throw new InvalidOperationException($"This nest already has a drawing named '{drawing.Name}'.");
}
drawingsAdded = true;
}
///
/// Adds the drawings when they are not yet added and places a copy of every part on
/// exactly where it was copied from, joined in its common-line
/// groups again. Returns the placed parts.
///
public IReadOnlyList PlaceInPlace(Plate plate)
{
ArgumentNullException.ThrowIfNull(plate);
AddDrawings();
var placed = Parts.Select(p => (Part)p.Clone()).ToList();
placed.ForEach(plate.Parts.Add);
foreach (var (members, kerf) in CommonLines)
plate.JoinCommonLine(members.Select(i => placed[i]), kerf);
return placed;
}
}
}