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

namespace Ntp.Common.Process
{
    public sealed class Job
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Job" /> class.
        /// </summary>
        /// <param name="description">Description.</param>
        /// <param name="schedule">Schedule.</param>
        /// <param name="log">Log.</param>
        public Job(JobDescription description, JobScheduleDescription schedule, LogBase log)
        {
            lock (NextJobLocker)
            {
                JobId = nextJobId++;
            }

            Description = description;
            Schedule = schedule;
            this.log = log;

            RunCount = 0;
        }

        private static readonly object NextJobLocker = new object();
        private static int nextJobId = 1;

        private readonly LogBase log;
        private TimeSpan time = new TimeSpan(0);

        /// <summary>
        /// Gets the job identifier.
        /// </summary>
        /// <value>The job identifier.</value>
        public int JobId { get; }

        /// <summary>
        /// Gets the schedule.
        /// </summary>
        /// <value>The schedule.</value>
        public JobScheduleDescription Schedule { get; }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <value>The description.</value>
        public JobDescription Description { get; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Job" /> is queued for run.
        /// </summary>
        /// <value><c>true</c> if scheduled; otherwise, <c>false</c>.</value>
        public bool Queued { get; internal set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Job" /> has been postponed.
        /// </summary>
        /// <value><c>true</c> if postponed; otherwise, <c>false</c>.</value>
        public bool Postponed { get; internal set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Job" /> is running.
        /// </summary>
        /// <value><c>true</c> if running; otherwise, <c>false</c>.</value>
        public bool Running { get; private set; }

        /// <summary>
        /// Gets the time this this <see cref="Job" /> was started.
        /// </summary>
        /// <value>The started.</value>
        public DateTime Started { get; private set; }

        /// <summary>
        /// Gets the number of times this <see cref="Job" /> have been executed.
        /// </summary>
        /// <value>The run count.</value>
        public int RunCount { get; private set; }

        /// <summary>
        /// Gets the current state of this <see cref="Job" />.
        /// </summary>
        /// <value>The state.</value>
        public string State
        {
            get
            {
                if (Running)
                    return "running";
                if (Postponed)
                    return "postponed";

                return Queued ? "queued" : "stopped";
            }
        }

        /// <summary>
        /// Gets the time this <see cref="Job" /> have currently been running.
        /// </summary>
        /// <value>The runtime.</value>
        public string Runtime => Running ? DateTime.Now.Subtract(Started).ToString() : string.Empty;

        /// <summary>
        /// Gets the total time this <see cref="Job" /> have been running.
        /// </summary>
        /// <value>The runtime.</value>
        public string TotalRuntime => Running ? (DateTime.Now.Subtract(Started) + time).ToString() : time.ToString();

        /// <summary>
        /// Execute this <see cref="Job" />.
        /// </summary>
        public void Execute()
        {
            Started = DateTime.Now;

            // Narrow scope to reduce thread interference
            var threadStart = DateTime.Now;

            Queued = false;
            Postponed = false;
            Running = true;
            RunCount++;

            bool error = false;

            try
            {
                Description.Execute();
            }
            catch (Exception e)
            {
                error = true;
                log.JobError(this, e);
            }
            finally
            {
                Running = false;
            }

            time += DateTime.Now.Subtract(threadStart);
            log.JobExecutionStatus(this, error);
        }

        public static void Reset()
        {
            lock (NextJobLocker)
            {
                nextJobId = 1;
            }
        }

        /// <summary>
        /// Returns a <see cref="string" /> that represents the current <see cref="Job" />.
        /// </summary>
        /// <returns>A <see cref="string" /> that represents the current <see cref="Job" />.</returns>
        public override string ToString()
        {
            var name = string.IsNullOrWhiteSpace(Description.Name) ? string.Empty : " " + Description.Name;
            return $"{Description.JobType} job{name}";
        }
    }
}