//
// SignalHandler.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 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.Threading;
using Ntp.Interop;
using Ntp.Log;

namespace Ntp.Common
{
    public sealed class SignalHandler : IApplicationController
    {
        public SignalHandler(string name, LogBase log)
        {
            this.name = name;
            this.log = log;
            reload = false;
            stopped = false;
        }

        private readonly LogBase log;
        private readonly string name;
        private bool reload;
        private bool stopped;

        public bool Reload
        {
            get { return reload; }
        }

        public bool Stopped
        {
            get { return stopped; }
        }

        public event EventHandler<EventArgs> ExitApplication;

        private void RaiseExitApplicationEvent()
        {
            stopped = true;

            if (ExitApplication != null)
            {
                ExitApplication(this, EventArgs.Empty);
            }
        }

        public void Start()
        {
            var signalHandler = new Thread(Execute);
            signalHandler.Start();
        }

        private void Execute()
        {
            bool loop = true;

            while (loop)
            {
                try
                {
                    switch (InterProcess.Wait(name, log))
                    {
                        case InterProcess.Signal.Exit:
                            loop = false;
                            RaiseExitApplicationEvent();
                            log.WriteLine(Message.Closing, Severity.Notice);
                            break;
                        case InterProcess.Signal.Reload:
                            reload = true;
                            loop = false;
                            RaiseExitApplicationEvent();
                            log.WriteLine(Message.Reloading, Severity.Notice);
                            break;
                        case InterProcess.Signal.Refresh:
                            var thread = new Thread(() =>
                            {
                                LogFactory.Suspend();
                                Thread.Sleep(30000);
                                LogFactory.Resume();
                            });
                            log.WriteLine(Message.Refreshing, Severity.Notice);
                            thread.Start();
                            break;
                        case InterProcess.Signal.Notify:
                            // TODO
                            break;
                        case InterProcess.Signal.Error:
                            loop = false;
                            log.WriteLine(Message.ErrorInterProc, Severity.Warn);
                            RaiseExitApplicationEvent();
                            break;
                        default:
                            log.WriteLine(Message.ErrorSignal, Severity.Warn);
                            break;
                    }
                }
                catch (Exception e)
                {
                    log.WriteLine(Message.ErrorHandler, Severity.Error);
                    log.WriteLine(e.Message, Severity.Debug);
                    log.WriteLine(e, Severity.Trace);
                    loop = false;
                    RaiseExitApplicationEvent();
                }
            }
        }
    }
}