using System;
using System.Net.Sockets;

namespace EonaCat.Logger.GrayLog
{
    // This file is part of the EonaCat project(s) which is released under the Apache License.
    // See the LICENSE file or go to https://EonaCat.com/License for full license details.

    /// <summary>
    /// Syslog server.
    /// </summary>
    public class GrayLogServer
    {
        /// <summary>
        /// Hostname.
        /// </summary>
        public string Hostname
        {
            get
            {
                return _Hostname;
            }

            set
            {
                if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(Hostname));
                _Hostname = value;

                SetUdp();
            }
        }

        /// <summary>
        /// UDP port.
        /// </summary>
        public int Port
        {
            get
            {
                return _Port;
            }
            set
            {
                if (value < 0) throw new ArgumentException("Port must be zero or greater.");
                _Port = value;

                SetUdp();
            }
        }

        /// <summary>
        /// IP:port of the server.
        /// </summary>
        public string IpPort
        {
            get
            {
                return _Hostname + ":" + _Port;
            }
        }

        internal readonly object SendLock = new object();
        internal UdpClient Udp = null;
        private string _Hostname = "127.0.0.1";
        private int _Port = 12201;

        /// <summary>
        /// Instantiate the object.
        /// </summary>
        public GrayLogServer()
        {
        }

        /// <summary>
        /// Instantiate the object.
        /// </summary>
        /// <param name="hostname">Hostname.</param>
        /// <param name="port">Port.</param>
        public GrayLogServer(string hostname = "127.0.0.1", int port = 12201)
        {
            Hostname = hostname;
            Port = port;
        }

        private void SetUdp()
        {
            Udp = null;
            Udp = new UdpClient(_Hostname, _Port);
        }
    }
}
