// 
// 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 System.Collections.Generic;
using System.Linq;
using System.Threading;
using Ntp.Common.App;
using Ntp.Common.Log;

namespace Ntp.Common.Process
{
    public sealed class Cluster : IDisposable
    {
        public Cluster(
            Scheduler scheduler,
            IApplicationController controller,
            IEnumerable<IRequest> peers,
            LogBase log)
        {
            this.scheduler = scheduler;
            this.peers = peers;
            this.log = log;

            waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            controller.ExitApplication += (sender, e) =>
            {
                run = false;
                waitHandle.Set();
                scheduler.WaitHandle.Set();
            };
        }

        private readonly LogBase log;
        private readonly IEnumerable<IRequest> peers;
        private readonly Scheduler scheduler;
        private readonly EventWaitHandle waitHandle;
        private bool run;

        public void Activate()
        {
            bool activated = true;
            if (peers.Count() != 0)
            {
                log.ClusterStart();
            }

            run = true;
            while (run)
            {
                bool otherActive = false;
                foreach (var request in peers)
                {
                    try
                    {
                        string answer = request.Send("ping");

                        if (answer != null && answer == "*" && activated)
                        {
                            log.ClusterNodeAlive(request);
                        }
                        else if (answer != null && answer == "active" && activated)
                        {
                            log.ClusterNodeActive(request);
                        }
                        else if (activated)
                        {
                            log.ClusterNodeDead(request);
                        }

                        if (answer != null && answer == "active")
                        {
                            otherActive = true;
                        }
                    }
                    catch (Exception e)
                    {
                        log.ClusterNodeError(request, e);
                    }
                }

                if (!otherActive)
                {
                    try
                    {
                        scheduler.RunOneCycle();
                    }
                    catch (Exception e)
                    {
                        log.ClusterError(e);
                        return;
                    }
                }
                else
                {
                    waitHandle.WaitOne(10000);
                }

                // This node is now active and no longer "activated"
                activated = false;
            }

            scheduler.Stop();
        }

        #region IDisposable Support

        private bool disposedValue;

        private void Dispose(bool disposing)
        {
            if (disposedValue)
                return;

            if (disposing)
            {
                waitHandle.Dispose();
            }

            disposedValue = true;
        }

        ~Cluster()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}