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

namespace Ntp.Common.System
{
    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;

        public bool Reload { get; private set; }

        public bool Stopped { get; private set; }

        public event EventHandler<EventArgs> ExitApplication;

        public void Start()
        {
            // Signal handler is only supported on Unix platforms
            if (Environment.OSVersion.Platform != PlatformID.Unix)
                return;

            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;
                            log.SignalClosing();
                            RaiseExitApplicationEvent();
                            break;
                        case InterProcess.Signal.Reload:
                            Reload = true;
                            loop = false;
                            log.SignalReloading();
                            RaiseExitApplicationEvent();
                            break;
                        case InterProcess.Signal.Refresh:
                            var thread = new Thread(() =>
                            {
                                LogFactory.Suspend();
                                Thread.Sleep(30000);
                                LogFactory.Resume();
                            });
                            log.SignalRefreshing();
                            thread.Start();
                            break;
                        case InterProcess.Signal.Notify:
                            break;
                        case InterProcess.Signal.Error:
                            loop = false;
                            log.SignalInterProcError();
                            RaiseExitApplicationEvent();
                            break;
                        default:
                            log.UnexpectedSignal();
                            break;
                    }
                }
                catch (Exception e)
                {
                    log.SignalHandlerError(e);
                    loop = false;
                    RaiseExitApplicationEvent();
                }
            }
        }

        private void RaiseExitApplicationEvent()
        {
            Stopped = true;
            ExitApplication?.Invoke(this, EventArgs.Empty);
        }
    }
}