82 lines
3.0 KiB
C#
82 lines
3.0 KiB
C#
using System.Linq;
|
|
using System.Xml.Serialization;
|
|
using System.Collections.Generic;
|
|
|
|
using Avalonia;
|
|
|
|
using BFR.Helpers;
|
|
using BFR.DataModels;
|
|
using System;
|
|
|
|
namespace BFR.Operations
|
|
{
|
|
public class Number : Operation
|
|
{
|
|
public override string Name => nameof(Number);
|
|
public override string Description => "Numbers all file names according to how they are sorted.";
|
|
|
|
public static readonly AvaloniaProperty<NumberMode> ModeProperty =
|
|
AvaloniaProperty.Register<MainWindow, NumberMode>(nameof(Mode), NumberMode.Prepend);
|
|
public NumberMode Mode { get => GetValue(ModeProperty); set => SetValue(ModeProperty, value); }
|
|
|
|
[XmlIgnore]
|
|
public NumberOperationMode[] Modes => NumberOperationMode.Modes;
|
|
|
|
public int InsertPosition { get; set; } = 0;
|
|
public int Increment { get; set; } = 1;
|
|
public int StartIndex { get; set; } = 1;
|
|
public int Padding { get; set; } = 0;
|
|
public bool AutoPadding { get; set; } = false;
|
|
public bool FullName { get; set; } = false;
|
|
public bool UseRegex { get; set; } = false;
|
|
public string Pattern { get; set; } = "";
|
|
|
|
protected override void ApplyToInternal(IList<FileModel> files)
|
|
{
|
|
var index = StartIndex;
|
|
var padding = AutoPadding
|
|
? (StartIndex + Increment * (files.Count - 1)).ToString().Length
|
|
: Padding;
|
|
|
|
// Fail conditions: Out of bounds insert
|
|
var shortestLength = files.Min(x => FullName ? x.FullName.Length : x.Name.Length);
|
|
if (Mode == NumberMode.Insert && InsertPosition > shortestLength) throw new OperationException($"First N can't be greater than the shortest file name length ({shortestLength}).");
|
|
|
|
// Regex Failure
|
|
if (Mode == NumberMode.Replace && UseRegex)
|
|
try { "".Replace(Pattern, "", true, false); }
|
|
catch (Exception) { throw new OperationException("Invalid Regex Pattern."); }
|
|
|
|
// Apply operation
|
|
foreach (var file in files)
|
|
{
|
|
var newName = FullName ? file.FullName : file.Name;
|
|
var text = PadInteger(index, padding);
|
|
|
|
newName = Mode switch
|
|
{
|
|
NumberMode.Prepend => $"{text}{newName}",
|
|
NumberMode.Append => $"{newName}{text}",
|
|
NumberMode.Insert => newName.Insert(InsertPosition, text),
|
|
NumberMode.Replace => newName.Replace(Pattern, text, UseRegex, false),
|
|
_ => newName
|
|
};
|
|
|
|
if (FullName) file.FullName = newName;
|
|
else file.Name = newName;
|
|
|
|
index += Increment;
|
|
}
|
|
}
|
|
|
|
private static string PadInteger(int value, int padding)
|
|
{
|
|
var valueString = value.ToString();
|
|
while (valueString.Length < padding)
|
|
valueString = $"0{valueString}";
|
|
|
|
return valueString;
|
|
}
|
|
}
|
|
}
|