2019-11-23 17:40:55 +00:00
using System ;
using System.Linq ;
2019-11-22 18:18:07 +00:00
using System.Xml.Serialization ;
2019-11-21 18:46:33 +00:00
using System.Collections.Generic ;
using Avalonia ;
using BFR.Helpers ;
using BFR.DataModels ;
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 =
2019-11-22 18:12:28 +00:00
AvaloniaProperty . Register < MainWindow , NumberMode > ( nameof ( Mode ) , NumberMode . Prepend ) ;
2019-11-21 18:46:33 +00:00
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 ;
2019-11-22 18:18:07 +00:00
// 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
2019-11-21 18:46:33 +00:00
foreach ( var file in files )
{
var newName = FullName ? file . FullName : file . Name ;
var text = PadInteger ( index , padding ) ;
newName = Mode switch
{
2019-11-22 18:12:28 +00:00
NumberMode . Prepend = > $"{text}{newName}" ,
NumberMode . Append = > $"{newName}{text}" ,
2019-11-21 18:46:33 +00:00
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 ;
}
}
}