//
// Cluster.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.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using Ntp.Analyzer.Log;
using Ntp.System;

namespace Ntp.Process
{
    public sealed class Cluster
    {
        public Cluster (
            string name,
            Scheduler scheduler,
            IEnumerable<IRequest> peers,
            LogBase log)
        {
            this.name = name;
            this.scheduler = scheduler;
            this.peers = peers;
            this.log = log;
            waitHandle = new EventWaitHandle (false, EventResetMode.AutoReset);
        }

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

        public void Activate ()
        {
            log.WriteLine ("Starting cluster module.", Severity.Info);

            Thread killSwitch = new Thread (KillSwitch);
            killSwitch.Start ();
            run = true;

            // TODO: Move to public scope (ApplicationState)
            bool activated = true;

            while (run) {

                bool otherActive = false;

                foreach (IRequest request in peers) {

                    try {
                        string answer = request.Send ("ping");

                        if (answer != null && answer == "*" && activated) {
                            log.WriteLine ("Cluster node alive: " + request, Severity.Notice);
                        } else if (answer != null && answer == "active" && activated) {
                            log.WriteLine ("Cluster node active: " + request, Severity.Notice);
                        } else if (activated) {
                            log.WriteLine ("Cluster node dead: " + request, Severity.Notice);
                        }

                        if (answer != null && answer == "active") {
                            otherActive = true;
                        }
                    } catch (Exception e) {
                        log.WriteLine ("Error while contacting cluster node " + request, Severity.Warn);
                        log.WriteLine (e, Severity.Trace);
                    } 
                }

                if (!otherActive) {
                    log.WriteLine ("No other nodes active. Activting node.", Severity.Debug);

                    try {
                        scheduler.RunOneCycle ();
                    } catch (Exception e) {
                        log.WriteLine ("Error in scheduler module. Arborting.", Severity.Error);
                        log.WriteLine (e.ToString (), Severity.Error);
                        log.WriteLine (e, Severity.Trace);
                        return;
                    }
                } else {
                    log.WriteLine ("Other node active. Going to fallback mode.", Severity.Debug);
                    waitHandle.WaitOne (10000);
                }

                activated = false;
            }               
        }

        public void KillSwitch ()
        {
            try {
                InterLock.Wait (name, log);
                waitHandle.Set ();
                scheduler.WaitHandle.Set ();
                run = false;
            } catch (Exception e) {
                log.WriteLine ("Error in mutux.", Severity.Error);
                log.WriteLine (e.ToString (), Severity.Error);
                log.WriteLine (e, Severity.Trace);
            }

            log.WriteLine ("Closing down.", Severity.Notice);
        }
    }
}
