//  
//   Rebex Sample Code License
// 
//   Copyright 2025, 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 Rebex.Net;

namespace Rebex.Samples
{
    /// <summary>
    /// This sample connects to a Syslog server, sends a message and disconnects.
    /// </summary>
    class Program
    {
        static SyslogTransportProtocol Protocol;
        static string Hostname;
        static int Port;

        static void Main(string[] args)
        {
            // set the trial license key
            Rebex.Licensing.Key = Rebex.Samples.TrialKey.Key;


            // parse arguments
            if (!ParseArguments(args))
            {
                ShowHelp();
                return;
            }

            // create new logger
            using (var logger = new SysLogWriter(Hostname, Port, Protocol)
            {
                Level = LogLevel.Debug, // log at 'debug' level
                Facility = SyslogFacility.User, // use 'user-level' facility
                Severity = SyslogSeverity.Informational, // use 'informational' severity
            })
            {
                // plug the logger into a Rebex object
                // for example, negotiate a TLS with "test.rebex.net"
                using (var socket = new TlsSocket())
                {
                    string host = "test.rebex.net";
                    int port = 443;

                    // assign logger first
                    socket.LogWriter = logger;

                    Console.WriteLine("Connecting to {0}:{1}.", host, port);
                    socket.Connect(host, port);

                    Console.WriteLine("Negotiating TLS.");
                    socket.Negotiate();

                    Console.WriteLine("TLS negotiated successfully.");
                }
            }
        }


        static bool ParseArguments(string[] args)
        {
            if (args == null || args.Length < 2 || args.Length > 2)
            {
                Console.WriteLine("ERROR: Wrong number of arguments.");
                return false;
            }

            if (!ParseProtocol(args[0]))
                return false;

            if (!ParseAddress(args[1]))
                return false;

            return true;
        }

        private static bool ParseProtocol(string protocol)
        {
            switch (protocol.ToUpperInvariant())
            {
                case "UDP": Protocol = SyslogTransportProtocol.Udp; return true;
                case "TCP": Protocol = SyslogTransportProtocol.Tcp; return true;
                case "TLS": Protocol = SyslogTransportProtocol.Tls; return true;
                default: Console.WriteLine("ERROR: Invalid protocol."); return false;
            }
        }

        private static bool ParseAddress(string address)
        {
            if (address.Contains(":"))
            {
                var parts = address.Split(':');
                if (parts.Length != 2)
                {
                    Console.WriteLine("ERROR: Invalid address.");
                    return false;
                }

                Hostname = parts[0];
                if (!int.TryParse(parts[1], out Port) || Port <= 0 || Port > ushort.MaxValue)
                {
                    Console.WriteLine("ERROR: Invalid port.");
                    return false;
                }
            }
            else
            {
                Hostname = address;
                Port = Protocol == SyslogTransportProtocol.Tls
                     ? SyslogServer.DefaultTlsPort
                     : SyslogServer.DefaultPort;
            }
            return true;
        }

        static void ShowHelp()
        {
            Console.WriteLine();
            Console.WriteLine("Usage: SysLogWriter protocol host[:port]");
            Console.WriteLine();
            Console.WriteLine("Protocol can be one of: UDP, TCP, TLS");
            Console.WriteLine();
            Console.WriteLine("Example: SysLogWriter UDP localhost");
            Console.WriteLine("Example: SysLogWriter TCP localhost:514");
            Console.WriteLine("Example: SysLogWriter TLS localhost:6514");
        }
    }
}
