//
// Job.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013 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 Ntp.Analyzer.Log;

namespace Ntp.Process
{
    public sealed class Job
    {
        private static readonly Object nextJobLocker = new object ();
        private static int nextJobId = 1;

        /// <summary>
        /// Initializes a new instance of the <see cref="Ntp.Process.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++;
            }

            this.description = description;
            this.schedule = schedule;
            this.log = log;

            runCount = 0;
        }

        private readonly int jobId;
        private readonly JobDescription description;
        private readonly JobScheduleDescription schedule;
        private readonly LogBase log;
        private TimeSpan time = new TimeSpan (0);
        private DateTime started;
        private int runCount;

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

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

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

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Ntp.Process.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="Ntp.Process.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="Ntp.Process.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="Ntp.Process.Job" /> was started.
        /// </summary>
        /// <value>The started.</value>
        public DateTime Started {
            get { return started; }
        }

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

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

        /// <summary>
        /// Gets the time this <see cref="Ntp.Process.Job" /> have currently been running.
        /// </summary>
        /// <value>The runtime.</value>
        public string Runtime {
            get { return Running ? (DateTime.Now.Subtract (started)).ToString () : String.Empty; }
        }

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

        /// <summary>
        /// Execute this <see cref="Ntp.Process.Job" />.
        /// </summary>
        public void Execute ()
        {
            started = DateTime.Now;
            Queued = false;
            Postponed = false;
            Running = true;
            runCount++;

            log.WriteLine (String.Format ("{0} -> Executing", this), Severity.Debug);

            try {
                description.Execute ();
            } catch (Exception ex) {
                log.WriteLine ("Error while executing " + ToString (), Severity.Error);
                log.WriteLine (ex.Message, Severity.Debug);
            } finally {
                Running = false;
            }

            time += DateTime.Now.Subtract (started);
            log.WriteLine (String.Format ("{0} -> Done", this), Severity.Debug);
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents the current <see cref="Ntp.Process.Job"/>.
        /// </summary>
        /// <returns>A <see cref="System.String"/> that represents the current <see cref="Ntp.Process.Job"/>.</returns>
        public override string ToString ()
        {
            return String.Format ("{0} {1} ({2})",
                                  jobId.ToString ("00"),
                                  description.Name,
                                  description.JobType);
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents the configuration of the current <see cref="Ntp.Process.Job"/>.
        /// </summary>
        /// <returns>A <see cref="System.String"/> that represents the configuration of the current <see cref="Ntp.Process.Job"/>.</returns>
        public string ConfigString {
            get {
                return String.Format (
                    "{0} {1} ({2}), initial run {3}, fixed run {4}, frequency {5}",
                    jobId.ToString ("00"),
                    description.Name,
                    description.JobType,
                    schedule.InitialRun ? 1 : 0,
                    schedule.FixedRun ? 1 : 0,
                    schedule.Frequency);
            }
        }
    }
}
