//
// NtpdcImporter.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-2016 Carsten Sonne Larsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// 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.Diagnostics;
using System.IO;
using System.Linq;
using Ntp.Analyzer.Log;
using Ntp.Analyzer.Objects;
using Ntp.Analyzer.Data;
using Ntp.System;

namespace Ntp.Analyzer.Data.Live
{
    /// <summary>
    /// Ntpdc importer.
    /// </summary>
    public sealed class NtpdcImporter : HostValueImporter
    {
        public NtpdcImporter (string address, Host host, ReadingBulk bulk, LogBase log)
            : base(log)
        {
            this.address = address;
            this.host = host;
            this.bulk = bulk;
        }

        private readonly string address;
        private readonly Object locker = new Object ();
        private readonly ReadingBulk bulk;
        private readonly List<HostReading> entries = new List<HostReading> ();
        private readonly Host host;
        private List<Peer> peers;

        /// <summary>
        /// Gets the imported entries.
        /// </summary>
        /// <value>
        /// The entries.
        /// </value>
        public override HostReading[] Entries {
            get {
                lock (locker) {
                    return entries.ToArray ();
                }
            }
        }

        private void Initialize ()
        {
            if (host == null)
                return;

            peers = DataFace.Instance.Peers.ToList ();
        }

        /// <summary>
        /// Import data from the specified server.
        /// </summary>
        public override void Import ()
        {
            lock (locker) {
                Initialize ();
                {
                    ShellCommand command = new ShellCommand (
                                               "ntpdc",
                                               "-nc loopinfo -c sysinfo " + address,
                                               Log) {
                        ErrorMessage = "Unexpected error while reading host stats"
                    };

                    StreamReader reader = command.Execute ();
                    if (reader == null)
                        return;

                    ReadFromStream (reader);
                }
            }
        }

        /// <summary>
        /// Reads from stream.
        /// </summary>
        /// <param name="reader">Reader.</param>
        /// <remarks>
        /// * offset:               -0.000284 s
        /// * frequency:            -2.994 ppm
        /// 2 poll adjust:          30
        /// watchdog timer:       173 s
        /// 2 system peer:          ntp1.gbg.netnod.se
        /// system peer mode:     client
        /// leap indicator:       00
        /// stratum:              2
        /// precision:            -19
        /// root distance:        0.02441 s
        /// root dispersion:      0.03212 s
        /// reference ID:         [192.36.133.17]
        /// reference time:       d57eb121.eca883cb  Wed, Jul  3 2013 16:18:09.924
        /// system flags:         auth monitor ntp kernel stats
        /// * jitter:               0.000198 s
        /// * stability:            0.000 ppm
        /// broadcastdelay:       0.000000 s
        /// authdelay:            0.000037 s
        /// </remarks>
        private void ReadFromStream (StreamReader reader)
        {
            string peerIp = null;
            double offset = 0;
            double frequency = 0;
            double jitter = 0;
            double stability = 0;

            while (reader.Peek () != -1) {
                string line = reader.ReadLine ();

                if (line != null && line.Trim () == String.Empty)
                    continue;

                if (line == null || line.Length < 24)
                    continue;

                string name = line.Substring (0, 22).Replace (":", String.Empty).TrimEnd ();
                string value = line.Substring (22).TrimEnd ();

                switch (name) {
                case "system peer":
                    peerIp = value.Trim ();
                    break;
                case "offset":
                    offset = Convert.ToDouble (value.Replace ("s", String.Empty).Trim ());
                    break;
                case "frequency":
                    frequency = Convert.ToDouble (value.Replace ("ppm", String.Empty).Trim ());
                    break;
                case "jitter":
                    jitter = Convert.ToDouble (value.Replace ("s", String.Empty).Trim ());
                    break;
                case "stability":
                    stability = Convert.ToDouble (value.Replace ("ppm", String.Empty).Trim ());
                    break;
                }
            }

            IEnumerable<Peer> peerList = peers.Where (p => p.Ip == peerIp);

            Peer peer;

            switch (peerList.Count ()) {
            case 1:
                peer = peerList.Single ();
                break;
            case 0:
                Log.WriteLine (String.Format (
                    "Could not import data from {0}. Peer with IP {1} was not found in database.",
                    host.Name, peerIp),
                    Severity.Error);
                return;
            default:
                Log.WriteLine (String.Format (
                    "Could not import data from {0}. Found more than one peer with IP {1} in database.",
                    host.Name, peerIp),
                    Severity.Error);
                return;
            }

            HostReading reading = new HostReading (host, peer, bulk, offset, jitter, frequency, stability);

            entries.Add (reading);
        }
    }
}