using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using eSuite.WorkBench.Services;
using eSuite.WorkBench.WpfHelper;

namespace eSuite.WorkBench.Commands;

public class DeleteBranchVersionCommand : AsyncCommandBase
{
    private readonly MainWindowViewModel _mainWindowViewModel;
    private readonly IContainerRegistryClient _containerRegistryClient;

    public DeleteBranchVersionCommand(MainWindowViewModel mainWindowViewModel, IContainerRegistryClient containerRegistryClient, Action<Exception> onException, EventHandler<FeedbackEventArgs> addFeedbackMessage) : base(onException)
    {
        FeedbackMessage += addFeedbackMessage;
        _mainWindowViewModel = mainWindowViewModel;
        _containerRegistryClient = containerRegistryClient;
    }

    protected override async Task ExecuteAsync(object parameter)
    {
        if (_mainWindowViewModel.SelectedBranch == null)
        {
            return;
        }
        
        var branchFeature = BranchFeature();
        DoFeedbackMessage($"Deleting {branchFeature}");

        if (branchFeature == "master")
        {
            branchFeature = string.Empty;
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableWebUiTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.webui", imageName);
            DoFeedbackMessage($"WebUi: {imageName}");
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableApiTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.api", imageName);
            DoFeedbackMessage($"API: {imageName}");
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableDbMigratorTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.database.migrator", imageName);
            DoFeedbackMessage($"Migrator: {imageName}");
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableSchedulerTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.scheduler", imageName);
            DoFeedbackMessage($"Scheduler: {imageName}");
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableMessageProcessorTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.messageprocessor", imageName);
            DoFeedbackMessage($"Message Processor: {imageName}");
        }

        foreach (var imageName in GetAllAvailableVersions(branchFeature, _mainWindowViewModel.AvailableProxyTags))
        {
            await _containerRegistryClient.DeleteImageAsync("e-suite.proxy", imageName);
            DoFeedbackMessage($"Proxy: {imageName}");
        }

        DoFeedbackMessage($"{branchFeature} deleted");
    }

    private string BranchFeature()
    {
        //var branchVersion = parameter as Branch;
        var branchVersion = _mainWindowViewModel.SelectedBranch;
        var branchFeature = $"{branchVersion.Parent?.BranchName}-{branchVersion.BranchName}".TrimStart('-');
        return branchFeature;
    }

    public override bool CanExecute(object parameter)
    {
        if (!_mainWindowViewModel.DeveloperMode)
            return false;

        if (_mainWindowViewModel.SelectedBranch == null)
            return false;

        if (!base.CanExecute(parameter))
            return false;
        
        var branchFeature = BranchFeature();
        switch (branchFeature)
        {
            case "master":
            case "develop":
                return false;
            default:
                return true;
        }
    }

    private static IEnumerable<string> GetAllAvailableVersions(string branchFeature, IEnumerable<string> availableTags)
    {
        var tags = branchFeature == string.Empty ?
            availableTags.Where(x => !x.Contains("-")) :
            availableTags.Where(x => x.Contains(branchFeature));

        return tags;
    }

    private static readonly Regex Regex = new Regex(@"\d+\.\d+\.\d+.\d+");

    private static List<long> CalcXNumbers(string value)
    {
        var parts = Regex.Match(value).Value.Split('.');

        return parts.Select(part => long.Parse(part)).ToList();
    }
}