// 
// 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.Collections.Generic;
using System.Linq;
using Ntp.Analyzer.Data;
using Ntp.Analyzer.Objects;
using Ntp.Common.Log;

namespace Ntp.Analyzer.Import
{
    public sealed class NtpctlHostImporter : NtpctlImporter<HostReading>
    {
        internal NtpctlHostImporter(Host host, ReadingBulk bulk, LogBase log)
            : base(host.Id, log)
        {
            this.host = host;
            this.bulk = bulk;
        }

        private readonly ReadingBulk bulk;
        private readonly Host host;
        private List<Peer> peers;

        protected override string ErrorMessage => LogMessage.ImportHostError;

        protected override void Initialize()
        {
            base.Initialize();

            if (host == null)
                return;

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

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

            // Find SysPeer
            while (Reader.Peek() != -1)
            {
                string peer = Reader.ReadLine();
                string stat = Reader.ReadLine();
                var entry = ParseLines(peer, stat);

                if (entry.TallyCode != TallyCode.SysPeer)
                    continue;

                CreateEntry(entry);
                return;
            }

            Log.OpenNtpUnsynced();
        }

        private void CreateEntry(AssociationEntry entry)
        {
            IEnumerable<Peer> peerList = peers.Where(p => p.Ip == entry.Remote).ToList();

            Peer peer;

            switch (peerList.Count())
            {
                case 1:
                    peer = peerList.Single();
                    break;
                case 0:
                    Log.PeerNotFound(host.Name, entry.Remote);
                    return;
                default:
                    Log.MultiplePeersFound(host.Name, entry.Remote);
                    return;
            }

            Log.Syncing(host.Name, peer.Name);

            var reading = new HostReading(host, peer, bulk, entry.Offset, entry.Jitter);
            Entries.Add(reading);
        }
    }
}