// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// 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.Objects;
using Ntp.Common.Log;

namespace Ntp.Analyzer.Import
{
    /// <summary>
    /// Ntpq mapper parses status importLines from ntpq into objects.
    /// </summary>
    public sealed class NtpqPeerImporter : Importer<AssociationEntry>
    {
        internal NtpqPeerImporter(string address, int hostId, LogBase log)
            : base(log)
        {
            this.address = address;
            this.hostId = hostId;
        }

        private readonly string address;
        private readonly int hostId;

        protected override string Command => "ntpq";

        protected override string Arguments => "-np " + address;

        protected override string ErrorMessage => LogMessage.ImportPeerError;

        protected override void ReadFromStream()
        {
            // Skip header
            Reader.ReadLine();
            Reader.ReadLine();

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

                if (string.IsNullOrWhiteSpace(line))
                    continue;

                var entry = ParseLine(line);
                Entries.Add(entry);
            }
        }

        private static int CalcLastPoll(string line)
        {
            string lastPollString = line.Substring(38, 4);

            char lastPollUnit = lastPollString.Substring(lastPollString.Length - 1, 1)[0];
            string lastPollValue = lastPollString.Substring(0, lastPollString.Length - 1).Trim();

            switch (lastPollUnit)
            {
                case 'm':
                    return Convert.ToInt32(lastPollValue)*60;
                case 'h':
                    return Convert.ToInt32(lastPollValue)*60*60;
                case 'd':
                    return Convert.ToInt32(lastPollValue)*60*60*24;
                case '-':
                    return -1;
                default:
                    return Convert.ToInt32(lastPollString);
            }
        }

        private AssociationEntry ParseLine(string line)
        {
            char state = line[0];
            string remote = line.Substring(1, 16).Trim();
            string refid = line.Substring(17, 16).Trim();
            int stratus = Convert.ToInt32(line.Substring(33, 2).Trim());
            char t = line[36];
            int lastPoll = CalcLastPoll(line);
            int pollFrequency = Convert.ToInt32(line.Substring(43, 4).Trim());
            int reach = Convert.ToInt32(line.Substring(49, 3).Trim());
            double delay = Convert.ToDouble(line.Substring(53, 8).Trim());
            double offset = Convert.ToDouble(line.Substring(61, 9).Trim());
            double jitter = Convert.ToDouble(line.Substring(70, 8).Trim());

            var entry = new AssociationEntry(
                hostId, state, remote, refid, stratus, t,
                lastPoll, pollFrequency, reach, delay, offset, jitter);

            return entry;
        }
    }
}