//
// IoStatsImporter.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 Ntp.Analyzer.Localize;
using Ntp.Log;
using Ntp.Analyzer.Objects;

namespace Ntp.Analyzer.Import
{
    public sealed class IoStatsImporter : Importer<IoStatsEntry>
    {
        internal IoStatsImporter(string address, bool ntpq, LogBase log)
            : base(log)
        {
            this.address = address;
            this.ntpq = ntpq;
        }

        private readonly string address;
        private readonly bool ntpq;

        protected override string Command
        {
            get { return ntpq ? "ntpq" : "ntpdc"; }
        }

        protected override string Arguments
        {
            get { return "-c iostats " + address; }
        }

        protected override string ErrorMessage
        {
            get { return LogMessage.ImportIoError; }
        }

        /// <summary>
        /// Reads from stream.
        /// </summary>
        /// <remarks>
        /// time since reset:     2676627
        /// receive buffers:      10
        /// free receive buffers: 9
        /// used receive buffers: 0
        /// low water refills:    1
        /// dropped packets:      2091
        /// ignored packets:      26
        /// received packets:     36174080
        /// packets sent:         34848739
        /// packets not sent:     56457
        /// interrupts handled:   35712727
        /// received by int:      35712727
        /// </remarks>
        protected override void ReadFromStream()
        {
            int timeSinceReset = -1;
            int receiveBuffers = -1;
            int freeReceiveBuffers = -1;
            int usedReceiveBuffers = -1;
            int lowWaterRefills = -1;
            int droppedPackets = -1;
            int ignoredPackets = -1;
            int receivedPackets = -1;
            int packetsSent = -1;
            int packetsNotSent = -1;
            int interruptsHandled = -1;
            int receivedByInt = -1;

            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();

                int parsedValue;

                if (!Int32.TryParse(value, out parsedValue))
                {
                    parsedValue = -2;
                }

                switch (name)
                {
                    case "time since reset":
                        timeSinceReset = parsedValue;
                        break;
                    case "receive buffers":
                        receiveBuffers = parsedValue;
                        break;
                    case "free receive buffers":
                        freeReceiveBuffers = parsedValue;
                        break;
                    case "used receive buffers":
                        usedReceiveBuffers = parsedValue;
                        break;
                    case "low water refills":
                        lowWaterRefills = parsedValue;
                        break;
                    case "dropped packets":
                        droppedPackets = parsedValue;
                        break;
                    case "ignored packets":
                        ignoredPackets = parsedValue;
                        break;
                    case "received packets":
                        receivedPackets = parsedValue;
                        break;
                    case "packets sent":
                        packetsSent = parsedValue;
                        break;
                    case "packets not sent":
                    case "packet send failures":
                        packetsNotSent = parsedValue;
                        break;
                    case "input wakeups":
                    case "interrupts handled":
                        interruptsHandled = parsedValue;
                        break;
                    case "useful input wakeups":
                    case "received by int":
                        receivedByInt = parsedValue;
                        break;
                    default:
                        Log.WriteLine(String.Format(LogMessage.ImportNtpValueError, name),
                            Severity.Warn);
                        break;
                }
            }

            Entries.Add(new IoStatsEntry(
                timeSinceReset,
                receiveBuffers,
                freeReceiveBuffers,
                usedReceiveBuffers,
                lowWaterRefills,
                droppedPackets,
                ignoredPackets,
                receivedPackets,
                packetsSent,
                packetsNotSent,
                interruptsHandled,
                receivedByInt));
        }
    }
}