//  
//   Rebex Sample Code License
// 
//   Copyright 2026, REBEX CR s.r.o.
//   All rights reserved.
//   https://www.rebex.net/
// 
//   Permission to use, copy, modify, and/or distribute this software for any
//   purpose with or without fee is hereby granted.
// 
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//   OTHER DEALINGS IN THE SOFTWARE.
// 

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace Rebex.Samples
{
    /// <summary>
    /// Represents a TLS proxy.
    /// </summary>
    public class TlsProxy : IDisposable
    {
        private const string TLS_PROXY_RUNNING = "TLS Proxy is already running.";
        private const int MAX_PENDING_CONNECTIONS = int.MaxValue;

        private readonly object _sync; // synchronization object
        private readonly TlsProxyConfiguration _config; // proxy configuration
        private readonly Socket _listener; // socket listener for accepting incoming connections
        private readonly Dictionary<int, Tunnel> _tunnels; // list of active tunnels

        private CancellationTokenSource _cancellation; // can cancel all operations, also identifies whether the proxy is running
        private bool _disposed; // indicates whether the proxy object was disposed

        /// <summary>
        /// Initializes the proxy object with the specified configuration.
        /// </summary>
        public TlsProxy(TlsProxyConfiguration config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            _sync = new object();
            _config = config;
            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _tunnels = new Dictionary<int, Tunnel>();
        }

        /// <summary>
        /// Starts the TLS proxy.
        /// </summary>
        public void Start()
        {
            lock (_sync)
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException(GetType().Name);
                }
                if (_cancellation == null)
                {
                    _cancellation = new CancellationTokenSource();
                }
                else
                {
                    throw new InvalidOperationException(TLS_PROXY_RUNNING);
                }
            }

            StartListener();
        }

        /// <summary>
        /// Disposes the proxy object.
        /// </summary>
        void IDisposable.Dispose()
        {
            lock (_sync)
            {
                if (_disposed)
                    return;

                _disposed = true;

                if (_cancellation != null)
                    _cancellation.Cancel();
            }

            ClearAsync().Wait(); // wait for resource cleanup
        }

        /// <summary>
        /// Clears necessary internal objects and lists.
        /// </summary>
        private async Task ClearAsync()
        {
            try { _listener.Close(); }
            catch { } // we are stopping the proxy, we don't need to process exceptions now

            IEnumerable<Tunnel> tunnels;
            lock (_sync)
            {
                tunnels = _tunnels.Values;
            }

            foreach (var tunnel in tunnels)
            {
                try { await tunnel.CloseAsync().ConfigureAwait(false); }
                catch { } // we are stopping the proxy, we don't need to process exceptions now
            }

            lock (_sync)
            {
                _tunnels.Clear();
            }
        }

        /// <summary>
        /// Starts socket listener.
        /// </summary>
        private void StartListener()
        {
            Log(LogLevel.Info, "Listening at {0} (forwarding to {1}) ...", _config.ListeningAddress, _config.TargetAddress);

            try
            {
                _listener.Bind(_config.ListeningAddress);
                _listener.Listen(MAX_PENDING_CONNECTIONS);

                var acceptCallback = GetAcceptSocketCallback(_listener);
                _listener.BeginAccept(acceptCallback, null);
            }
            catch (Exception ex)
            {
                if (!_disposed)
                {
                    Log(LogLevel.Error, "Error while starting proxy: {0}", ex);
                }
            }
        }

        /// <summary>
        /// Handles newly accepted connections.
        /// </summary>
        private AsyncCallback GetAcceptSocketCallback(Socket listener)
        {
            AsyncCallback callback = null;
            callback = ar =>
            {
                // accept new connection
                Socket socket = null;
                try
                {
                    socket = listener.EndAccept(ar);
                }
                catch (ObjectDisposedException ex)
                {
                    if (!_disposed)
                    {
                        Log(LogLevel.Error, "Error while accepting connection: {0}", ex);
                    }
                    return;
                }
                finally
                {
                    if (!_disposed)
                    {
                        listener.BeginAccept(callback, null);
                    }
                }

                // start the tunnel, log error on failure
                StartTunnel(socket).ContinueWith(TaskHelpers.GetTaskLogErrorFunc(Log, "Start tunnel failed"),
                                                 TaskContinuationOptions.OnlyOnFaulted);
            };
            return callback;
        }

        /// <summary>
        /// Initializes new Tunnel object and starts data forwarding.
        /// </summary>
        private async Task StartTunnel(Socket incomingSocket)
        {
            bool success = false;
            Tunnel tunnel = null;
            try
            {
                Log(LogLevel.Info, "Connection from {0} accepted on {1}.", incomingSocket.RemoteEndPoint, incomingSocket.LocalEndPoint);

                // initialize new Tunnel object
                tunnel = new Tunnel(incomingSocket, _config, _cancellation.Token, OnTunnelClosed);

                // start forwarding
                await tunnel.Start().ConfigureAwait(false);

                // add tunnel to the list of tunnels
                success = OnTunnelStarted(tunnel);
            }
            catch (Exception ex)
            {
                if (!_disposed)
                {
                    if (tunnel != null)
                        Log(LogLevel.Error, "Error while starting tunnel({1}): {0}", ex, tunnel.Id);
                    else
                        Log(LogLevel.Error, "Error while starting tunnel: {0}", ex);
                }
            }
            finally
            {
                if (!success)
                {
                    if (tunnel != null)
                        await tunnel.CloseAsync().ConfigureAwait(false);
                    else
                        incomingSocket.Close();
                }
            }
        }

        /// <summary>
        /// Adds new tunnel to the list of tunnels.
        /// </summary>
        private bool OnTunnelStarted(Tunnel tunnel)
        {
            lock (_sync)
            {
                if (!_disposed)
                {
                    _tunnels.Add(tunnel.Id, tunnel);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Removes closed tunnel form the list of tunnels.
        /// </summary>
        private void OnTunnelClosed(int id)
        {
            lock (_sync)
            {
                if (!_disposed)
                {
                    _tunnels.Remove(id);
                }
            }
        }

        /// <summary>
        /// Helper logging method.
        /// </summary>
        private void Log(LogLevel level, string format, params object[] args)
        {
            var log = _config.LogWriter;
            if (log != null)
            {
                Log(level, string.Format(format, args));
            }
        }

        /// <summary>
        /// Helper logging method.
        /// </summary>
        private void Log(LogLevel level, string message)
        {
            var log = _config.LogWriter;
            if (log != null)
            {
                log.Write(level, typeof(TlsProxy), 0, "INFO", message);
            }
        }
    }
}
