aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/Operation/JobHandler.cs
blob: fce815bc378cdc2fba42c8aed9079854754252ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Editors
{
    /// <summary>
    /// Represents different modes for the <see cref="ElementsEditor"/>.
    /// </summary>
    public enum ElementsEditorMode
    {
        /// <summary>
        /// The editor will behave as normal.
        /// </summary>
        Default,
        /// <summary>
        /// Hides the rulers, auto editor size, disables zooming and panning.
        /// </summary>
        AdvancedCanvas,
    }
}
'n250' href='#n250'>250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Logging;
using Tango.PMR.Printing;

namespace Tango.Integration.Operation
{
    /// <summary>
    /// Represents a <see cref="MachineOperator"/> job handler.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    public class JobHandler : ExtendedObject
    {
        protected Action _cancelAction;
        protected List<Segment> _effectiveSegments;
        protected String _lastStatusMessage;
        protected int _last_unit;
        protected bool _finalizing;
        protected JobHandlerModes _mode;
        protected double _last_progress;
        protected const int PROGRESS_REPORT_RANGE_METERS = 5;
        protected bool loggedContinueMessage;

        #region Events

        /// <summary>
        /// Occurs when a job status has been received.
        /// </summary>
        public event EventHandler<RunningJobStatus> StatusChanged;

        /// <summary>
        /// Occurs when the job has failed.
        /// </summary>
        public event EventHandler<Exception> Failed;

        /// <summary>
        /// Occurs when the job has completed successfully.
        /// </summary>
        public event EventHandler Completed;

        /// <summary>
        /// Occurs when the job has been canceled.
        /// </summary>
        public event EventHandler Canceled;

        /// <summary>
        /// Occurs when the job has been canceled, failed or completed.
        /// </summary>
        public event EventHandler Stopped;

        /// <summary>
        /// Occurs when rolling the dryer buffer.
        /// </summary>
        public event EventHandler Finalizing;

        /// <summary>
        /// Occurs when a segment has started.
        /// </summary>
        public event EventHandler<Segment> SegmentStarted;

        /// <summary>
        /// Occurs when a segment has completed.
        /// </summary>
        public event EventHandler<Segment> SegmentCompleted;

        /// <summary>
        /// Occurs when a unit completes.
        /// </summary>
        public event EventHandler<int> UnitCompleted;

        /// <summary>
        /// Occurs when the job is set to 1 segment per spool and it's time to replace the spool.
        /// </summary>
        public event EventHandler<SpoolChangeRequiredEventArgs> SpoolChangeRequired;

        /// <summary>
        /// Occurs when <see cref="CanCancel"/> has changed.
        /// </summary>
        public event EventHandler CanCancelChanged;

        #endregion

        #region Properties

        private JobStatus _jobStatus;
        /// <summary>
        /// Gets or sets the current job status that was used to invalidate this handler.
        /// </summary>
        public JobStatus JobStatus
        {
            get { return _jobStatus; }
            set { _jobStatus = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets a value indicating whether this handler job has been canceled.
        /// </summary>
        public bool IsCanceled { get; internal set; }

        private bool _canCancel;
        /// <summary>
        /// Gets a value indicating whether the job can be canceled.
        /// </summary>
        public bool CanCancel
        {
            get { return _canCancel; }
            internal set { _canCancel = value; RaisePropertyChangedAuto(); CanCancelChanged?.Invoke(this, new EventArgs()); }
        }

        /// <summary>
        /// Gets the process parameters.
        /// </summary>
        public ProcessParametersTable ProcessParameters { get; private set; }

        private RunningJobStatus _Status;
        /// <summary>
        /// Gets the current status.
        /// </summary>
        public RunningJobStatus Status
        {
            get { return _Status; }
            internal set { _Status = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets the job.
        /// </summary>
        public Job Job { get; private set; }

        /// <summary>
        /// Gets the PMR job ticket.
        /// </summary>
        public JobTicket JobTicket { get; private set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="JobHandler"/> class.
        /// </summary>
        public JobHandler()
        {
            CanCancel = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="JobHandler"/> class.
        /// </summary>
        /// <param name="cancelAction">The cancel action.</param>
        public JobHandler(Action cancelAction, Job job, JobTicket jobTicket, ProcessParametersTable processParameters, JobHandlerModes mode) : this()
        {
            _mode = mode;

            ProcessParameters = processParameters;
            Job = job;
            JobTicket = jobTicket;

            foreach (var s in Job.Segments)
            {
                s.Started = false;
                s.Completed = false;
                s.RemainingTime = TimeSpan.FromSeconds(0);
            }

            _effectiveSegments = Job.EffectiveSegments.ToList();

            _cancelAction = () => { cancelAction(); };

            Status = new RunningJobStatus();

            Status.TotalTime = job.GetEstimatedDuration(processParameters);
            Status.RemainingUnits = job.NumberOfUnits;
            Status.TotalProgress = Job.LengthIncludingNumberOfUnits + processParameters.DryerBufferLengthMeters;
            Status.FinalizingTotalProgress = processParameters.DryerBufferLengthMeters;
            Status.TotalProgressWithoutFinalization = Job.LengthIncludingNumberOfUnits;
            Status.Progress = 0;
            Status.RemainingTime = Status.TotalTime;
            Status.RemainingProgress = Status.TotalProgress;
            Status.CurrentUnitSegments = _effectiveSegments.ToList();
            Status.SettingUpTotalProgress = processParameters.DryerBufferLengthMeters;
            Status.TotalProgressMinusSettingUp = Job.LengthIncludingNumberOfUnits;
            Status.IsSettingUp = true;

            if (mode == JobHandlerModes.Finalization)
            {
                Status.CurrentUnitTotalProgress = Job.Length;
            }
            else
            {
                Status.CurrentUnitTotalProgress = Status.SettingUpTotalProgress;
            }

            if (Job.EnableInterSegment && Job.NumberOfUnits > 1)
            {
                Status.CurrentUnitSegments.Add(Job.CreateInterSegment(Job.InterSegmentLength));
            }

            //Create all segments
            int segment_index = 1;

            for (int j = 0; j < Math.Max(Job.NumberOfUnits, 1); j++)
            {
                for (int i = 0; i < _effectiveSegments.Count; i++)
                {
                    Segment seg = _effectiveSegments[i].Clone();
                    seg.EstimatedDuration = seg.GetEstimatedDuration(processParameters);
                    seg.SegmentIndex = segment_index++;
                    Status.Segments.Add(seg);
                }

                if (Job.EnableInterSegment)
                {
                    var inter_segment = Job.CreateInterSegment(Job.InterSegmentLength);
                    inter_segment.SegmentIndex = segment_index++;
                    Status.Segments.Add(inter_segment);
                }
            }

            var last_segment = Status.Segments.Last();

            if (last_segment.IsInterSegment)
            {
                Status.Segments.Remove(last_segment);
            }

            Status.CurrentSegment = Status.Segments.First();
        }

        #endregion

        #region Internal Methods

        /// <summary>
        /// Raises the status received event.
        /// </summary>
        /// <param name="status">The status.</param>
        public void RaiseStatusReceived(JobStatus status)
        {
            InvalidateJobProgress(status);
        }

        /// <summary>
        /// Raises the failed event.
        /// </summary>
        /// <param name="ex">The ex.</param>
        public void RaiseFailed(Exception ex)
        {
            LogManager.Log($"Job failed at position {Status.Progress}/{Status.TotalProgress}...");
            Status.IsFailed = true;
            RaiseStatusChanged();
            RaisePropertyChanged(nameof(Status));
            Failed?.Invoke(this, ex);
            Stopped?.Invoke(this, new EventArgs());
        }

        /// <summary>
        /// Raises the completed event.
        /// </summary>
        public void RaiseCompleted()
        {
            //This will compensate on any missing progress from Shlomo, but also will tell the wrong progress if job is really completed with a large progress mistake.
            // Might be worth to compensate only on small drifts like the below (ProgressMinusSettingsUp)...
            //InvalidateJobProgress(new JobStatus()
            //{
            //    Progress = Status.TotalProgress,
            //    CurrentSegmentIndex = 0,
            //});

            LogManager.Log($"Job completed at position {Status.Progress}/{Status.TotalProgress}...");

            //If drift is smaller than 10cm auto correct it.
            if (Math.Abs(Status.TotalProgressMinusSettingUp - Status.ProgressMinusSettingUp) < 0.1)
            {
                LogManager.Log($"Job completed with a small drift in the progress minus setting up calculation. ({Status.ProgressMinusSettingUp}/{Status.TotalProgressMinusSettingUp}). Compensating...");
                Status.ProgressMinusSettingUp = Status.TotalProgressMinusSettingUp;
            }
            //If the overall progress is correct? Fix the minus setting up. There is a problem with the delta calc!
            else if (Status.Progress == Status.TotalProgress)
            {
                LogManager.Log($"Job completed with a small drift in the progress minus setting up calculation but the overall progress seems OK. ({Status.ProgressMinusSettingUp}/{Status.TotalProgressMinusSettingUp}). Compensating...");
                Status.ProgressMinusSettingUp = Status.TotalProgressMinusSettingUp;
            }

            Status.Segments.Last().Completed = true;
            Status.RemainingUnits = 0;
            Status.IsFinalizing = false;
            Status.IsCompleted = true;
            RaiseStatusChanged();
            RaisePropertyChanged(nameof(Status));
            Completed?.Invoke(this, new EventArgs());
            Stopped?.Invoke(this, new EventArgs());
        }

        /// <summary>
        /// Raises the canceled event.
        /// </summary>
        public void RaiseCanceled()
        {
            LogManager.Log($"Job canceled at position {Status.Progress}/{Status.TotalProgress}...");
            Status.IsCanceled = true;
            RaiseStatusChanged();
            RaisePropertyChanged(nameof(Status));
            Canceled?.Invoke(this, new EventArgs());
            Stopped?.Invoke(this, new EventArgs());
        }

        /// <summary>
        /// Raises the spool change required event.
        /// </summary>
        internal void RaiseSpoolChangeRequired(Action confirmAction, Action abortAction)
        {
            SpoolChangeRequired?.Invoke(this, new SpoolChangeRequiredEventArgs(confirmAction, abortAction)
            {
                CurrentSegment = Status.CurrentSegment.SegmentIndex,
                TotalSegments = Status.Segments.Count,
            });
        }

        #endregion

        #region Private Methods

        //protected virtual void InvalidateJobProgress(JobStatus s)
        //{
        //    JobStatus = s;
        //    bool invalidProgress = false;

        //    if (_last_progress != s.Progress)
        //    {
        //        if (s.Progress <= PROGRESS_REPORT_RANGE_METERS || s.Progress >= Status.TotalProgress - PROGRESS_REPORT_RANGE_METERS)
        //        {
        //            LogManager.Log($"Updating job progress {s.Progress}/{Status.TotalProgress}...");
        //        }
        //        else if (!loggedContinueMessage)
        //        {
        //            loggedContinueMessage = true;
        //            LogManager.Log($"Progress logging will continue {PROGRESS_REPORT_RANGE_METERS} meters before completion...");
        //        }
        //    }

        //    if (s.Progress < 0)
        //    {
        //        LogManager.Log($"Invalid job progress received '{s.Progress}'.", LogCategory.Error);
        //        invalidProgress = true;
        //    }

        //    if (s.Progress > Status.TotalProgress)
        //    {
        //        LogManager.Log($"Invalid job progress received '{s.Progress}' while total progress is '{Status.TotalProgress}'.", LogCategory.Error);
        //        invalidProgress = true;
        //    }

        //    if (s.Progress < _last_progress)
        //    {
        //        LogManager.Log($"Invalid job progress received '{s.Progress}' while last progress was '{_last_progress}'.");
        //        invalidProgress = true;
        //    }

        //    if (invalidProgress)
        //    {
        //        return;
        //    }

        //    _last_progress = s.Progress;

        //    //Job Status
        //    if (IsCanceled)
        //    {
        //        Status.IsCanceled = IsCanceled;
        //        RaiseStatusChanged();
        //        return;
        //    }

        //    List<Segment> unit_segments = new List<Segment>();
        //    double delta = s.Progress - Status.Progress;

        //    Status.Progress = s.Progress;
        //    Status.RemainingTime = Status.TotalTime - Job.TranslateProgressToTime(Status.Progress, ProcessParameters);
        //    Status.RemainingProgress = Status.TotalProgress - Status.Progress;

        //    if (Status.SettingUpProgress < Status.SettingUpTotalProgress)
        //    {
        //        Status.SettingUpProgress += delta;
        //    }
        //    else
        //    {
        //        if (Status.IsSettingUp && Status.Progress > 0)
        //        {
        //            Status.IsSettingUp = false;
        //        }

        //        Status.ProgressMinusSettingUp += delta;
        //    }

        //    if (s.Progress < Job.LengthIncludingNumberOfUnits || _mode == JobHandlerModes.SettingUp)
        //    {
        //        Status.ProgressWithoutFinalization += delta;

        //        unit_segments = _effectiveSegments.ToList();

        //        if (Job.EnableInterSegment && Job.NumberOfUnits > 1 && Status.RemainingUnits > 1)
        //        {
        //            unit_segments.Add(Job.CreateInterSegment(Job.InterSegmentLength));
        //        }

        //        if (unit_segments.Count != Status.CurrentUnitSegments.Count)
        //        {
        //            Status.CurrentUnitSegments = unit_segments;
        //        }

        //        Status.CurrentUnitTotalProgress = Status.RemainingUnits > 1 && Job.EnableInterSegment ? Job.Length + (Job.InterSegmentLength) : Job.Length;

        //        if (_mode == JobHandlerModes.Finalization)
        //        {
        //            Status.CurrentUnitProgress += delta;
        //        }
        //        else
        //        {
        //            if (!Status.IsSettingUp)
        //            {
        //                Status.CurrentUnitProgress += delta;
        //            }
        //        }

        //        if (Status.CurrentUnitProgress >= Status.CurrentUnitTotalProgress)
        //        {
        //            Status.CurrentUnitProgress = 0;
        //            Status.CurrentUnit++;
        //        }

        //        Status.RemainingUnits = Job.NumberOfUnits - Status.CurrentUnit;

        //        if (s.Message != _lastStatusMessage && s.Message != String.Empty)
        //        {
        //            Status.Message = s.Message;
        //        }
        //        else
        //        {
        //            Status.Message = null;
        //        }

        //        _lastStatusMessage = s.Message;

        //        RaiseStatusChanged();

        //        //Segments Completion

        //        if (Status.CurrentUnit > _last_unit)
        //        {
        //            foreach (var segment in Status.CurrentUnitSegments)
        //            {
        //                segment.Started = false;
        //                segment.Completed = false;
        //            }

        //            if (Job.NumberOfUnits > 1)
        //            {
        //                RaiseUnitCompleted(_last_unit);
        //            }
        //        }

        //        _last_unit = Status.CurrentUnit;


        //        for (int i = 0; i < Status.CurrentUnitSegments.Count; i++)
        //        {
        //            Segment segment = Status.CurrentUnitSegments[i];
        //            double previousSegmentsLengthWithThis = Status.CurrentUnitSegments.Take(i + 1).Sum(x => x.LengthWithFactor);
        //            TimeSpan segmentsDuration = Job.TranslateProgressToTime(previousSegmentsLengthWithThis, ProcessParameters);
        //            TimeSpan segmentRemainingTime = segmentsDuration - Job.TranslateProgressToTime(Status.CurrentUnitProgress, ProcessParameters);

        //            if (i == 0 && Status.CurrentUnitProgress > 0)
        //            {
        //                if (!segment.Started)
        //                {
        //                    segment.Started = true;
        //                    RaiseSegmentStarted(segment);
        //                }
        //            }

        //            if (Status.CurrentUnitProgress >= previousSegmentsLengthWithThis)
        //            {
        //                if (!segment.Completed)
        //                {
        //                    segment.Completed = true;
        //                    RaiseSegmentCompleted(segment);
        //                }

        //                if (i < Status.CurrentUnitSegments.Count - 1)
        //                {
        //                    if (!Status.CurrentUnitSegments[i + 1].Started)
        //                    {
        //                        Status.CurrentUnitSegments[i + 1].Started = true;
        //                        RaiseSegmentStarted(Status.CurrentUnitSegments[i + 1]);
        //                    }
        //                }
        //            }

        //            if (segment.Started && !segment.Completed)
        //            {
        //                segment.RemainingTime = segmentRemainingTime;
        //            }
        //        }


        //        //Set Segment Completion for All Segments List
        //        for (int i = 0; i < Status.Segments.Count; i++)
        //        {
        //            Segment segment = Status.Segments[i];
        //            double previousSegmentsLengthWithThis = Status.Segments.Take(i + 1).Sum(x => x.LengthWithFactor);
        //            TimeSpan segmentsDuration = Job.TranslateProgressToTime(previousSegmentsLengthWithThis, ProcessParameters);
        //            TimeSpan segmentRemainingTime = segmentsDuration - Job.TranslateProgressToTime(Status.Progress, ProcessParameters);

        //            segment.Progress = Math.Min(Math.Max((previousSegmentsLengthWithThis - segment.Length - Status.Progress) * -1, 0), segment.Length);

        //            if (i == 0 && Status.Progress > 0)
        //            {
        //                if (!segment.Started)
        //                {
        //                    segment.Started = true;
        //                    Status.CurrentSegment = segment;
        //                }
        //            }

        //            if (Status.Progress >= previousSegmentsLengthWithThis)
        //            {
        //                if (!segment.Completed)
        //                {
        //                    segment.Completed = true;
        //                }

        //                if (i < Status.Segments.Count - 1)
        //                {
        //                    if (!Status.Segments[i + 1].Started)
        //                    {
        //                        Status.Segments[i + 1].Started = true;
        //                        Status.CurrentSegment = Status.Segments[i + 1];
        //                    }
        //                }
        //            }

        //            if (segment.Started && !segment.Completed)
        //            {
        //                segment.RemainingTime = segmentRemainingTime;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        //Finalizing
        //        if (!_finalizing)
        //        {
        //            _finalizing = true;
        //            Status.IsFinalizing = true;
        //            var last_Segment = _effectiveSegments.Last().Clone();
        //            last_Segment.Length = ProcessParameters.DryerBufferLengthMeters;
        //            Status.CurrentUnitSegments = new List<Segment> { last_Segment };
        //            Status.CurrentUnitTotalProgress = last_Segment.Length;
        //            Status.CurrentUnitProgress = 0;
        //            Status.ProgressWithoutFinalization = Status.TotalProgressWithoutFinalization;
        //            RaiseFinalizing();
        //        }

        //        Status.CurrentUnitProgress += delta;
        //        Status.FinalizingProgress += delta;
        //    }
        //}

        protected virtual void InvalidateJobProgress(JobStatus s)
        {
            JobStatus = s;

            if (_last_progress != s.Progress)
            {
                if (s.Progress <= PROGRESS_REPORT_RANGE_METERS || s.Progress >= Status.TotalProgress - PROGRESS_REPORT_RANGE_METERS)
                {
                    LogManager.Log($"Updating job progress {s.Progress}/{Status.TotalProgress}...");
                }
                else if (!loggedContinueMessage)
                {
                    loggedContinueMessage = true;
                    LogManager.Log($"Progress logging will continue {PROGRESS_REPORT_RANGE_METERS} meters before completion...");
                }
            }

            if (s.Progress < 0)
            {
                LogManager.Log($"Invalid job progress received '{s.Progress}'.", LogCategory.Error);
                return;
            }

            if (s.Progress > Status.TotalProgress)
            {
                LogManager.Log($"Invalid job progress received '{s.Progress}' while total progress is '{Status.TotalProgress}'.", LogCategory.Error);
                return;
            }

            if (s.Progress < _last_progress)
            {
                LogManager.Log($"Invalid job progress received '{s.Progress}' while last progress was '{_last_progress}'.");
            }

            _last_progress = s.Progress;

            List<Segment> unit_segments = new List<Segment>();

            Status.Progress = s.Progress;
            Status.RemainingTime = Status.TotalTime - Job.TranslateProgressToTime(Status.Progress, ProcessParameters);
            Status.RemainingProgress = Status.TotalProgress - Status.Progress;

            if (s.Progress < Status.SettingUpTotalProgress || Status.SettingUpProgress < Status.SettingUpTotalProgress)
            {
                Status.SettingUpProgress = Math.Min(s.Progress, this.Status.SettingUpTotalProgress);
                Status.IsSettingUp = true;
            }
            if (s.Progress >= Status.SettingUpTotalProgress)
            {
                if (Status.IsSettingUp && Status.Progress > 0)
                {
                    Status.IsSettingUp = false;
                }

                Status.ProgressMinusSettingUp = s.Progress - this.Status.SettingUpTotalProgress;
            }

            int units = (int)Math.Max(Job.NumberOfUnits, 1);

            if (s.Progress < Job.LengthIncludingNumberOfUnits || _mode == JobHandlerModes.SettingUp)
            {
                Status.ProgressWithoutFinalization = s.Progress;

                unit_segments = _effectiveSegments.ToList();
                Status.CurrentUnitProgress = 0.0;
                double previousUnitsLengthWithoutThis = 0.0;
                for (int index = 0; index < units; ++index)
                {
                    Status.CurrentUnit = index;
                    double unitLength = !Job.EnableInterSegment || index >= units - 1 ? Job.Length : Job.Length + Job.InterSegmentLength;
                    if (_mode == JobHandlerModes.Finalization)
                    {
                        if (s.Progress < unitLength + previousUnitsLengthWithoutThis)
                        {
                            Status.CurrentUnitProgress = s.Progress - previousUnitsLengthWithoutThis;
                            break;
                        }
                    }
                    else if (s.Progress <= previousUnitsLengthWithoutThis + unitLength + Status.SettingUpProgress)
                    {
                        if (!Status.IsSettingUp)
                        {
                            Status.CurrentUnitProgress = s.Progress - previousUnitsLengthWithoutThis - this.Status.SettingUpProgress;
                            break;
                        }
                        break;
                    }
                    previousUnitsLengthWithoutThis += unitLength;
                }
                Status.RemainingUnits = this.Job.NumberOfUnits - this.Status.CurrentUnit;

                if (Job.EnableInterSegment && Job.NumberOfUnits > 1 && Status.RemainingUnits > 1)
                {
                    unit_segments.Add(Job.CreateInterSegment(Job.InterSegmentLength));
                }

                if (unit_segments.Count != Status.CurrentUnitSegments.Count)
                {
                    Status.CurrentUnitSegments = unit_segments;
                }

                Status.CurrentUnitTotalProgress = Status.RemainingUnits > 1 && Job.EnableInterSegment ? Job.Length + (Job.InterSegmentLength) : Job.Length;

                if (s.Message != _lastStatusMessage && s.Message != String.Empty)
                {
                    Status.Message = s.Message;
                }
                else
                {
                    Status.Message = null;
                }

                _lastStatusMessage = s.Message;


                RaiseStatusChanged();

                //Segments Completion
                if (Status.CurrentUnit > _last_unit)
                {
                    foreach (var segment in Status.CurrentUnitSegments)
                    {
                        segment.Started = false;
                        segment.Completed = false;
                    }

                    if (Job.NumberOfUnits > 1)
                    {
                        RaiseUnitCompleted(_last_unit);
                    }
                }

                _last_unit = Status.CurrentUnit;


                for (int i = 0; i < Status.CurrentUnitSegments.Count; i++)
                {
                    Segment segment = Status.CurrentUnitSegments[i];
                    double previousSegmentsLengthWithThis = Status.CurrentUnitSegments.Take(i + 1).Sum(x => x.LengthWithFactor);
                    TimeSpan segmentsDuration = Job.TranslateProgressToTime(previousSegmentsLengthWithThis, ProcessParameters);
                    TimeSpan segmentRemainingTime = segmentsDuration - Job.TranslateProgressToTime(Status.CurrentUnitProgress, ProcessParameters);

                    if (i == 0 && Status.CurrentUnitProgress > 0)
                    {
                        if (!segment.Started)
                        {
                            segment.Started = true;
                            RaiseSegmentStarted(segment);
                        }
                    }

                    if (Status.CurrentUnitProgress >= previousSegmentsLengthWithThis)
                    {
                        if (!segment.Completed)
                        {
                            segment.Completed = true;
                            RaiseSegmentCompleted(segment);
                        }

                        if (i < Status.CurrentUnitSegments.Count - 1)
                        {
                            if (!Status.CurrentUnitSegments[i + 1].Started)
                            {
                                Status.CurrentUnitSegments[i + 1].Started = true;
                                RaiseSegmentStarted(Status.CurrentUnitSegments[i + 1]);
                            }
                        }
                    }

                    if (segment.Started && !segment.Completed)
                    {
                        segment.RemainingTime = segmentRemainingTime;
                    }
                }

                //Set Segment Completion for All Segments List
                for (int i = 0; i < Status.Segments.Count; i++)
                {
                    Segment segment = Status.Segments[i];
                    double previousSegmentsLengthWithThis = Status.Segments.Take(i + 1).Sum(x => x.LengthWithFactor);
                    TimeSpan segmentsDuration = Job.TranslateProgressToTime(previousSegmentsLengthWithThis, ProcessParameters);
                    TimeSpan segmentRemainingTime = segmentsDuration - Job.TranslateProgressToTime(Status.Progress, ProcessParameters);

                    segment.Progress = Math.Min(Math.Max((previousSegmentsLengthWithThis - segment.Length - Status.Progress) * -1, 0), segment.Length);

                    if (i == 0 && Status.Progress > 0)
                    {
                        if (!segment.Started)
                        {
                            segment.Started = true;
                            Status.CurrentSegment = segment;
                        }
                    }

                    if (Status.Progress >= previousSegmentsLengthWithThis)
                    {
                        if (!segment.Completed)
                        {
                            segment.Completed = true;
                        }

                        if (i < Status.Segments.Count - 1)
                        {
                            if (!Status.Segments[i + 1].Started)
                            {
                                Status.Segments[i + 1].Started = true;
                                Status.CurrentSegment = Status.Segments[i + 1];
                            }
                        }
                    }

                    if (segment.Started && !segment.Completed)
                    {
                        segment.RemainingTime = segmentRemainingTime;
                    }
                }
            }
            else
            {
                //Finalizing
                if (!_finalizing)
                {
                    _finalizing = true;
                    Status.IsFinalizing = true;
                    var last_Segment = _effectiveSegments.Last().Clone();
                    last_Segment.Length = ProcessParameters.DryerBufferLengthMeters;
                    Status.CurrentUnitSegments = new List<Segment> { last_Segment };
                    Status.CurrentUnitTotalProgress = last_Segment.Length;
                    Status.CurrentUnitProgress = 0;
                    Status.ProgressWithoutFinalization = Status.TotalProgressWithoutFinalization;
                    RaiseFinalizing();
                }

                Status.CurrentUnitProgress = s.Progress - Job.LengthIncludingNumberOfUnits;
                Status.FinalizingProgress = s.Progress - Status.TotalProgressWithoutFinalization;
            }
        }

        #endregion

        #region Protected Methods

        protected void RaiseStatusChanged()
        {
            StatusChanged?.Invoke(this, Status);
        }

        protected void RaiseSegmentStarted(Segment segment)
        {
            if (segment.IsInterSegment)
            {
                LogManager.Log($"Inter Segment started.");
            }
            else
            {
                LogManager.Log($"Segment {segment.SegmentIndex} of unit {Status.CurrentUnit + 1} started...");
            }

            SegmentStarted?.Invoke(this, segment);
        }

        protected void RaiseSegmentCompleted(Segment segment)
        {
            if (segment.IsInterSegment)
            {
                LogManager.Log($"Inter Segment completed.");
            }
            else
            {
                LogManager.Log($"Segment {segment.SegmentIndex} of unit {Status.CurrentUnit + 1} completed.");
            }
            SegmentCompleted?.Invoke(this, segment);
        }

        protected void RaiseUnitCompleted(int unit)
        {
            LogManager.Log($"Unit {unit + 1} completed...");
            UnitCompleted?.Invoke(this, unit);
        }

        protected void RaiseFinalizing()
        {
            LogManager.Log($"Finalizing...");
            Finalizing?.Invoke(this, new EventArgs());
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Cancels the associated job.
        /// </summary>
        public void Cancel()
        {
            _cancelAction();
        }

        #endregion
    }
}