using System;

namespace InABox.Core
{
    public class CoreTime : BaseObject, IEnclosedEntity
    {
        [TimeOfDayEditor]
        [EditorSequence(1)]
        [LoggableProperty(Format = "HH\\:mm")]
        public TimeSpan Start { get; set; }
        
        [DurationEditor(Summary = Summary.Sum)]
        [EditorSequence(2)]
        public TimeSpan Duration { get; set; }
        
        [TimeOfDayEditor]
        [EditorSequence(3)]
        [LoggableProperty(Format = "HH\\:mm")]
        public TimeSpan Finish { get; set; }


        private bool bChanging = false;
        
        protected override void DoPropertyChanged(string name, object? before, object? after)
        {
            base.DoPropertyChanged(name, before, after);
            
            if (bChanging)
                return;
            bChanging = true;
            
            if (String.Equals(name,nameof(Start)))
                Duration = Finish > (TimeSpan)after ? Finish.Subtract((TimeSpan)after) : new TimeSpan();

            else if (String.Equals(name,nameof(Finish)))
                Duration = (TimeSpan)after > Start ? ((TimeSpan)after).Subtract(Start) : new TimeSpan();
            
            else if (String.Equals(name,nameof(Duration)))
                Finish = Start.Add((TimeSpan)after);
            
            bChanging = false;
            
        }
        
    }
}