//  
//   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 Rebex.Net;
using Rebex;
using System.Text;

namespace Rebex.Samples
{
    /// <summary>
    /// This sample connects to an HTTPS server, sends 'GET' request, receives a response and displays it.
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            // set the trial license key
            Rebex.Licensing.Key = Rebex.Samples.TrialKey.Key;


            // parse arguments
            string hostport;
            if (args.Length == 0)
            {
                hostport = "test.rebex.net:443";
            }
            else
            {
                hostport = args[0];
                if (hostport.StartsWith("-") || !hostport.Contains(":"))
                {
                    Console.WriteLine("Usage: TlsEcho [host:port]");
                    Console.WriteLine("Example: TlsEcho test.rebex.net:443");
                    return;
                }
            }
            string[] split = hostport.Split(':');
            string host = split[0];
            int port = Convert.ToInt32(split[1]);

            // create an instance of TLS client socket
            using (var socket = new TlsClientSocket())
            {
                // log communication
                socket.LogWriter = new ConsoleLogWriter(LogLevel.Info);

                // connect to a server
                socket.Connect(host, port);
                socket.Negotiate();

                // send a request
                string requestTemplate = "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: close\r\n\r\n";
                byte[] request = Encoding.ASCII.GetBytes(string.Format(requestTemplate, host));
                socket.Send(request);

                // receive response and show it on console
                Console.WriteLine("---RESPONSE:---");
                byte[] response = new byte[4096];
                int count = socket.Receive(response);
                while (count > 0)
                {
                    Console.Write(Encoding.UTF8.GetString(response, 0, count));
                    count = socket.Receive(response);
                }
                Console.WriteLine();
            }
        }
    }
}
