//  
//   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;

namespace Rebex.Samples
{
    /// <summary>
    /// Provides logging capability. Logging messages are sent to desired Syslog server.
    /// </summary>
    public class SysLogWriter : LogWriterBase
    {
        private readonly SyslogClient _client;

        /// <summary>
        /// Facility level used for Syslog messages.
        /// </summary>
        public SyslogFacility Facility { get; set; }

        /// <summary>
        /// Severity level used for Syslog messages.
        /// </summary>
        public SyslogSeverity Severity { get; set; }

        /// <summary>
        /// Initializes new instance of the <see cref="SysLogWriter"/>.
        /// </summary>
        public SysLogWriter(string serverName, int port, SyslogTransportProtocol protocol)
        {
            // create Syslog client instance
            _client = new SyslogClient();

            try
            {
                // connect to desired Syslog server
                _client.Connect(serverName, port, protocol);
            }
            catch
            {
                _client.Close();
                throw;
            }
        }

        /// <summary>
        /// Writes the message into the log = sends message to the Syslog server.
        /// </summary>
        protected override void WriteMessage(string message)
        {
            // send the message
            _client.Send(message.TrimEnd(), Severity, Facility);
        }

        /// <summary>
        /// Releases all resources used by this instance.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _client.Close();
            }
            base.Dispose(disposing);
        }
    }
}
