// 
// 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;

namespace Ntp.Common.Process
{
    /// <summary>
    /// A description of job schedule rules.
    /// </summary>
    public sealed class JobScheduleDescription
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="JobScheduleDescription" /> class.
        /// </summary>
        /// <param name="initialRun">If set to <c>true</c> initial run.</param>
        /// <param name="fixedRun">If set to <c>true</c> fixed run.</param>
        /// <param name="frequency">Frequency in minutes.</param>
        public JobScheduleDescription(bool initialRun, bool fixedRun, int frequency)
        {
            InitialRun = initialRun || (frequency == 0);
            FixedRun = fixedRun;
            Frequency = frequency;
            initialRunDone = false;
        }

        private bool initialRunDone;

        /// <summary>
        /// Gets a value indicating whether this <see cref="JobScheduleDescription" />
        /// should do an initial run upon first call.
        /// </summary>
        /// <value><c>true</c> if initial run; otherwise, <c>false</c>.</value>
        public bool InitialRun { get; }

        /// <summary>
        /// Gets a value indicating whether this <see cref="JobScheduleDescription" /> has
        /// a fixed schedule frequence, eg. cannot be moved.
        /// </summary>
        /// <value><c>true</c> if fixed run; otherwise, <c>false</c>.</value>
        public bool FixedRun { get; }

        /// <summary>
        /// Gets the schedule frequency in minutes.
        /// </summary>
        /// <value>The frequency.</value>
        public int Frequency { get; }

        /// <summary>
        /// Gets a value indicating whether this description allow schedules to be moved.
        /// </summary>
        /// <value><c>true</c> if this instance can move; otherwise, <c>false</c>.</value>
        public bool CanMove => !(InitialRun && !initialRunDone) && !FixedRun;

        /// <summary>
        /// Calculates the time of next run according to description parameters.
        /// </summary>
        /// <returns>The next run.</returns>
        /// <param name="start">Start.</param>
        public DateTime CalculateNextRun(DateTime start)
        {
            if (Frequency == -1)
                return DateTime.MaxValue;
            if (Frequency == 0 || (InitialRun && !initialRunDone))
                return start;

            int multiplier = Convert.ToInt32(Math.Truncate((double) (start.Hour*60 + start.Minute)/Frequency));
            int startMinuttes = multiplier*Frequency;

            int hour = (startMinuttes + Frequency)/60;
            int minute = (startMinuttes + Frequency)%60;

            if (hour >= 24)
            {
                hour -= 24;
                start = start.AddDays(1);
            }

            if (minute >= 60)
            {
                minute -= 60;
                start = start.AddHours(1);
            }

            var next = new DateTime(start.Year, start.Month, start.Day, hour, minute, 0);

            return next;
        }

        /// <summary>
        /// Creates a new scheduled job based on description and parameters.
        /// </summary>
        /// <returns>The new.</returns>
        /// <param name="job">Job.</param>
        /// <param name="start">Start.</param>
        /// <param name="offset">Offset.</param>
        public ScheduledJob CreateNew(Job job, DateTime start, double offset)
        {
            if (InitialRun && !initialRunDone)
            {
                initialRunDone = true;
                return new ScheduledJob(job, start);
            }

            return new ScheduledJob(job, CalculateNextRun(start).AddMinutes(offset));
        }

        /// <summary>
        /// Creates a postponed job schedule.
        /// </summary>
        /// <returns>The postponed.</returns>
        /// <param name="job">Job.</param>
        public ScheduledJob CreatePostponed(Job job)
        {
            double offset = Frequency/100.0;

            if (offset > 2)
            {
                offset = 2;
            }
            else if (offset < 0.5)
            {
                offset = 0.5;
            }

            return new ScheduledJob(job, DateTime.Now.AddMinutes(offset));
        }
    }
}