using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace Aitex.Core.WCF;

public class WCFProxy
{
    public static void Using<T>(Action<T> action)
    {
        var factory = new ChannelFactory<T>("*");
        var client = (IClientChannel)factory.CreateChannel();
        try
        {
            action((T)client);
            client.Close();
            factory.Close();
        }
        catch (CommunicationException e)
        {
            client.Abort();
            throw;
        }
        catch (TimeoutException e)
        {
            client.Abort();
            throw;
        }
        catch (Exception e)
        {
            client.Abort();
            throw;
        }
    }
    
    public static async Task AsyncUsing<T>(Func<T, Task> action)
    {
        var factory = new ChannelFactory<T>("*");
        var client = (IClientChannel)factory.CreateChannel();
        try
        {
            await action((T)client);
            client.Close();
            factory.Close();
        }
        catch (CommunicationException e)
        {
            client.Abort();
            throw;
        }
        catch (TimeoutException e)
        {
            client.Abort();
            throw;
        }
        catch (Exception e)
        {
            client.Abort();
            throw;
        }
    }
}