bfr/BFR/Operations/Add.cs
2019-11-22 19:34:21 +01:00

53 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Linq;
using Avalonia;
using BFR.DataModels;
namespace BFR.Operations
{
public class Add : Operation
{
public override string Name => nameof(Add);
public override string Description => "Adds the specified text to the file name.";
[XmlIgnore]
public static readonly AvaloniaProperty<AddMode> ModeProperty =
AvaloniaProperty.Register<MainWindow, AddMode>(nameof(Mode), AddMode.Prepend);
public AddMode Mode { get => GetValue(ModeProperty); set => SetValue(ModeProperty, value); }
public AddOperationMode[] Modes => AddOperationMode.Modes;
public int InsertPosition { get; set; } = 0;
public string Text { get; set; } = "";
public bool FullName { get; set; } = false;
protected override void ApplyToInternal(IList<FileModel> files)
{
// Fail conditions: Out of bounds insert
var shortestLength = files.Min(x => FullName ? x.FullName.Length : x.Name.Length);
if (Mode == AddMode.Insert && InsertPosition > shortestLength) throw new OperationException($"Index can't be greater than the shortest file name length ({shortestLength}).");
// Apply operation
foreach (var file in files)
{
var newName = FullName ? file.FullName : file.Name;
newName = Mode switch
{
AddMode.Prepend => $"{Text}{newName}",
AddMode.Append => $"{newName}{Text}",
AddMode.Insert => newName.Insert(InsertPosition, Text),
_ => newName
};
if (FullName) file.FullName = newName;
else file.Name = newName;
}
}
}
}