namespace ADToGMConverter;

using System.Text;
using ADToGMConverter.Services;
using Melanchall.DryWetMidi.Core;
using Microsoft.Extensions.Logging;

class Program
{
    static private readonly ILogger<Program> logger = LoggerFactory.Create(x =>
    {
        x.AddConsole();
    }).CreateLogger<Program>();

    public static void Main(string[] args)
    {
        var inputFileName = args[0];
        var outputFileName = args[1];
        var trackName = args.Count() < 3 ? "Addictive Drums 2" : args[2];

        MidiFile? midiFile;

        try
        {
            midiFile = MidiFile.Read(inputFileName);
        }
        catch (Exception e)
        {
            logger.LogError($"Fatal at reading file: {e.Message}");
            throw;
        }

        if (midiFile == null)
        {
            logger.LogError($"Fatal at reading file: File is null");
            throw new NullReferenceException();
        }

        var trackResolver = new TrackResolver(midiFile.GetTrackChunks().ToList());

        var names = trackResolver.MapTrackChunksNames();

        logger.LogInformation($"{names.Values.Count()} tracks found");

        StringBuilder stringNames = new();
        foreach (var name in names)
        {
            stringNames.AppendLine($"{name.Key.ChunkId}: {name.Value}");
        }

        logger.LogInformation(stringNames.ToString());

        if (!names.Values.Contains(trackName))
        {
            logger.LogError($"Fatal: Track name {trackName} not found");
            return;
        }
        logger.LogInformation("Track name found! Converting to General MIDI drums mapping...");

         var drumTrack = names.First(x => x.Value == trackName).Key;
        
        // Преобразуем ноты AD2 -> GM
        TrackResolver.ConvertAd2ToGmDrums(drumTrack);

        // Сохраняем файл
        if (string.IsNullOrEmpty(outputFileName))
        {
            outputFileName = Path.Combine(
                Path.GetDirectoryName(inputFileName) ?? string.Empty,
                Path.GetFileNameWithoutExtension(inputFileName) + "_converted" + Path.GetExtension(inputFileName)
            );
        }

        try
        {
            midiFile.Write(outputFileName, true);
            logger.LogInformation($"Successfully converted! File saved as: {outputFileName}");
        }
        catch (Exception e)
        {
            logger.LogError($"Error saving file: {e.Message}");
        }
    }
}