// See https://aka.ms/new-console-template for more information

using System.Globalization;
using System.Reflection.Emit;
using TagLib;

Console.WriteLine("Hello, World!");

Environment.CurrentDirectory = "TargetFolder";
var dirs = Directory.GetDirectories(".").Select(p => p.Substring(2)).Where(p => p.StartsWith("[") == false).ToArray();

foreach (var dir in dirs)
{
    Console.WriteLine();

    var firstFile = Directory.GetFiles(dir, "*.flac").FirstOrDefault();
    if (firstFile == null)
    {
        if (Directory.GetFiles(dir).Length == 0)
        {
            Grey($"* delete empty dir `{dir}'");
            Directory.Delete(dir, false);
            continue;
        }
        Warn($"* Warn: flac file not found in top-level dir, its in sub dir? `{dir}'");
        continue;
    }

    var tag = TagLib.File.Create(firstFile);
    var xc = (TagLib.Ogg.XiphComment)tag.GetTag(TagTypes.Xiph);
    var v = xc.GetField("DATE").FirstOrDefault()?.Trim();
    if (false == DateTime.TryParseExact(v, "yyyy.MM.dd", null, DateTimeStyles.None, out var dt))
    {
        Warn($"* Warn: unable to get date from `{firstFile}' in `{dir}'");
        continue;
    }

    tag.Dispose();

    var parts = dir.Split(' ');

    if (parts.Length <= 2)
    {
        Warn($"* Warn: unable to process folder name for `{dir}'");
        continue;
    }

    var last1 = parts[^1];
    var last2 = parts[^2];

    string prefix;
    string remain;
    if (last2.StartsWith('[') && last2.EndsWith("]") && last1.StartsWith('(') && last1.EndsWith(')'))
    {
        var evt = last1;
        var label = last2;
        prefix = $"[{dt:yyMMdd}] [{evt[1..^1]}] {label}";
        remain = string.Join(" ", parts[..^2]);
    }
    else if (last1.StartsWith('[') && last1.EndsWith(']'))
    {
        var label = last1;

        prefix = $"[{dt:yyMMdd}] {label}";
        remain = string.Join(" ", parts[..^1]);
    }
    else
    {
        prefix = $"[{dt:yyMMdd}]";
        remain = string.Join(" ", parts);

        Warn("* Warn: unable to get label");
    }

    Console.WriteLine($"from >  {string.Empty.PadLeft(prefix.Length, ' ')}{dir}");

    Console.Write($"to   > {prefix} ");
    HiLight($"{remain}");
    Console.WriteLine();

    var final = prefix + " " + remain;

    try
    {
        Directory.Move(dir, final);
    }
    catch (Exception e)
    {
        Error("Err:" + e.Message);
    }
}


Console.WriteLine();
Console.Write("Finished. Press ENTER to exit");
Console.ReadLine();


static void HiLight(string msg) => ForegroundColor(ConsoleColor.Green, delegate { Console.Write(msg); });

static void Grey(string msg) => ForegroundColor(ConsoleColor.DarkGray, delegate { Console.WriteLine(msg); });

static void Warn(string msg) => ForegroundColor(ConsoleColor.Yellow, delegate { Console.WriteLine(msg); });

static void Error(string msg) => ForegroundColor(ConsoleColor.Red, delegate { Console.WriteLine(msg); });

static void ForegroundColor(ConsoleColor fg, Action action)
{
    var oldColor = Console.ForegroundColor;
    Console.ForegroundColor = fg;
    try
    {
        action();
    }
    finally
    {
        Console.ForegroundColor = oldColor;
    }
}
