aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.BL/Entities/Segment.cs
blob: 5a99442e4bc7042ebc11da77f14757d4723c9d64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Tango.BL.Interfaces;
using Tango.Core;
using Tango.Core.Threading;

namespace Tango.BL.Entities
{
    public partial class Segment : SegmentBase, ISegment
    {
        private double _lastLength;
        private LinearGradientBrush _brush;
        private ActionTimer _brushStopCollectionChangedActionTimer;

        #region Properties

        private TimeSpan _remainingTime;
        /// <summary>
        /// Gets or sets the remaining time for this segment to complete.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public TimeSpan RemainingTime
        {
            get { return _remainingTime; }
            set { _remainingTime = value; RaisePropertyChangedAuto(); }
        }

        private TimeSpan _estimatedDuration;
        /// <summary>
        /// Gets or sets the estimated duration for this segment to complete.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public TimeSpan EstimatedDuration
        {
            get { return _estimatedDuration; }
            set { _estimatedDuration = value; }
        }

        private double _progress;
        /// <summary>
        /// Gets or sets the segment progress within a running job.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public double Progress
        {
            get { return _progress; }
            set { _progress = value; RaisePropertyChangedAuto(); }
        }

        private bool _started;
        /// <summary>
        /// Gets or sets a value indicating whether this segment has started.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public bool Started
        {
            get { return _started; }
            set { _started = value; RaisePropertyChangedAuto(); }
        }

        private bool _completed;
        /// <summary>
        /// Gets or sets a value indicating whether this segment has completed.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public bool Completed
        {
            get { return _completed; }
            set { _completed = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets the segment brush.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public Brush SegmentBrush
        {
            get
            {
                return GetSegmentBrush();
            }
        }

        private bool _isInterSegment;
        /// <summary>
        /// Gets or sets a value indicating whether this segment is an inter segment.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public bool IsInterSegment
        {
            get { return _isInterSegment; }
            set { _isInterSegment = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets a value indicating whether this segment has any out of gamut brush stops.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public bool HasOutOfGamutBrushStop
        {
            get { return BrushStops.Any(x => x.IsOutOfGamut); }
        }

        /// <summary>
        /// Gets the length of this segment including the job length factor <see cref="JobBase.LengthPercentageFactor"/>.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public double LengthWithFactor
        {
            get { return Job != null && !IsInterSegment ? (Length + Length * (Job.LengthPercentageFactor / 100)) : Length; }
        }

        [NotMapped]
        [JsonIgnore]
        public String DisplayLengthWithFactor
        {
            get {
                double length = Job != null && !IsInterSegment ? (Length + Length * (Job.LengthPercentageFactor / 100)) : Length;
                return length.ToString("N0") + "m";
            }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Segment" /> class.
        /// </summary>
        public Segment() : base()
        {

        }

        #endregion

        #region Brush Stops Collection Changed

        private void BrushStops_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (_brushStopCollectionChangedActionTimer == null)
            {
                _brushStopCollectionChangedActionTimer = new ActionTimer(TimeSpan.FromMilliseconds(100));
            }

            _brushStopCollectionChangedActionTimer.ResetReplace(() =>
            {
                foreach (var stop in BrushStops.ToList())
                {
                    stop.RaiseOffsetChanged();
                }
                //Item#7059 - 
                //if (BrushStops.Count > 0)
                //{
                //    BrushStops.First().OffsetPercent = 0;
                //}
                //if (BrushStops.Count > 1)
                //{
                //    BrushStops.Last().OffsetPercent = 100;
                //}

                RaiseSegmentBrushChanged();
            });
        }

        #endregion

        #region Properties Changed

        /// <summary>
        /// Called when the Length has changed.
        /// </summary>
        /// <param name="length"></param>
        protected override void OnLengthChanged(double length)
        {
            base.OnLengthChanged(length);

            if (_lastLength != length)
            {
                BrushStops.ToList().ForEach(x => x.RaiseOffsetChanged());
                _lastLength = Length;
                RaisePropertyChanged(nameof(LengthWithFactor));
            }
        }

        /// <summary>
        /// Called when the BrushStops has changed.
        /// </summary>
        /// <param name="brushstops"></param>
        protected override void OnBrushStopsChanged(SynchronizedObservableCollection<BrushStop> brushstops)
        {
            base.OnBrushStopsChanged(brushstops);

            if (brushstops != null)
            {
                brushstops.CollectionChanged -= BrushStops_CollectionChanged;
                brushstops.CollectionChanged += BrushStops_CollectionChanged;

                foreach (var stop in brushstops.ToList())
                {
                    stop.RaiseOffsetChanged();
                }

                RaiseSegmentBrushChanged();
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets the segment brush.
        /// </summary>
        /// <returns></returns>
        public LinearGradientBrush GetSegmentBrush()
        {
            if (_brush == null || _brush.GradientStops.Count != BrushStops.Count)
            {
                GradientStopCollection stops = new GradientStopCollection();

                foreach (var stop in BrushStops.ToList().OrderBy(x => x.StopIndex).ToList())
                {
                    stops.Add(new GradientStop(stop.IsTransparent ? Colors.Transparent : stop.Color, stop.OffsetPercent / 100d));
                }

                LinearGradientBrush brush = new LinearGradientBrush();
                brush.StartPoint = new Point(0, 0);
                brush.EndPoint = new Point(1, 0);

                brush.GradientStops = stops;

                _brush = brush;
                return brush;
            }
            else
            {
                for (int i = 0; i < BrushStops.Count; i++)
                {
                    _brush.GradientStops[i].Color = BrushStops[i].IsTransparent ? Colors.Transparent : BrushStops[i].Color;
                    _brush.GradientStops[i].Offset = BrushStops[i].OffsetPercent / 100d;
                }

                return _brush;
            }
        }

        public void UpdateMiddleColorBrush()
        {
            if (BrushStops.Count == 5)
            {
                BrushStops[2].Color = GetRelativeRGB(BrushStops[1].Color, BrushStops[3].Color, 0, 1, 0.5);
            }
        }

        public BrushStop FirstBrushStop
        {
            get { if (BrushStops.Count == 1)//Intersegment?? - null
                return BrushStops[0];
            else if(BrushStops.Count >= 5)
                return BrushStops[1];
            else
                return null; }
        }

        public static Color GetRelativeRGB(Color first, Color second, double firstOffset, double secondOffset, double offset)
        {
            var color = new Color();
            var range = (secondOffset - firstOffset);
            var realoffset = offset - firstOffset;

            color.ScA = (float)(realoffset * (second.ScA - first.ScA) / range + first.ScA);
            color.ScR = (float)(realoffset * (second.ScR - first.ScR) / range + first.ScR);
            color.ScG = (float)(realoffset * (second.ScG - first.ScG) / range + first.ScG);
            color.ScB = (float)(realoffset * (second.ScB - first.ScB) / range + first.ScB);

            return color;
        }

        /// <summary>
        /// Raises the <see cref="SegmentBrush"/> property changed event.
        /// </summary>
        public void RaiseSegmentBrushChanged()
        {
            RaisePropertyChanged(nameof(SegmentBrush));
        }

        /// <summary>
        /// Raises the <see cref="LengthWithFactor"/> property changed event.
        /// </summary>
        public void RaiseLengthWithFactorChanged()
        {
            RaisePropertyChanged(nameof(LengthWithFactor));
        }

        /// <summary>
        /// Adds a new brush stop to this segment.
        /// </summary>
        /// <returns></returns>
        public BrushStop AddBrushStop()
        {
            BrushStop stop = new BrushStop();

            var lastStop = BrushStops.OrderBy(x => x.StopIndex).LastOrDefault();

            if (lastStop != null && lastStop.ColorSpace != null)
            {
                stop.ColorSpace = lastStop.ColorSpace;
            }
            else if (Job != null)
            {
                if (Job.ColorSpace != null)
                {
                    stop.ColorSpace = Job.ColorSpace;
                }
                else
                {
                    stop.ColorSpaceGuid = Job.ColorSpaceGuid;
                }
            }

            if (BrushStops.Count > 0)
            {
                stop.StopIndex = BrushStops.Max(x => x.StopIndex) + 1;
                stop.OffsetPercent = 100;
            }
            else
            {
                stop.StopIndex = 1;
            }

            stop.Segment = this;
            stop.Color = Colors.White;

            if (stop.ColorSpace != null)
            {
                if (stop.BrushColorSpace == Enumerations.ColorSpaces.LAB)
                {
                    stop.L = 100;
                    stop.A = 0;
                    stop.B = 0;
                }
            }

            BrushStops.Add(stop);

            return stop;
        }

        /// <summary>
        /// Gets the next segment.
        /// </summary>
        /// <returns></returns>
        public Segment GetNextSegment()
        {
            return Job.OrderedSegments.FirstOrDefault(x => x.SegmentIndex > SegmentIndex);
        }

        /// <summary>
        /// Gets the previous segment.
        /// </summary>
        /// <returns></returns>
        public Segment GetPreviousSegment()
        {
            return Job.OrderedSegments.LastOrDefault(x => x.SegmentIndex < SegmentIndex);
        }

        /// <summary>
        /// Gets the collection of previous segments.
        /// </summary>
        /// <returns></returns>
        public List<Segment> GetPreviousSegments()
        {
            return Job.OrderedSegments.Where(x => x.SegmentIndex < SegmentIndex).ToList();
        }

        /// <summary>
        /// Gets the estimated duration for this segment by the specified process parameters.
        /// </summary>
        /// <param name="processParameters">The process parameters.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">Process parameters dying speed cannot be zero.</exception>
        public TimeSpan GetEstimatedDuration(ProcessParametersTable processParameters)
        {
            if (processParameters.DyeingSpeed == 0)
            {
                throw new ArgumentException("Process parameters dying speed cannot be zero.");
            }
            return TimeSpan.FromSeconds(Length / (processParameters.DyeingSpeed / 100d));
        }

        /// <summary>
        /// Creates a GDI version of this segment brush.
        /// </summary>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns></returns>
        public System.Drawing.Brush CreateGdiBrush(int width, int height)
        {
            if (BrushStops.Count > 1)
            {
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.PointF(0, 0), new System.Drawing.Point(width, height), System.Drawing.Color.Black, System.Drawing.Color.Black);

                System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend();

                List<System.Drawing.Color> colors = new List<System.Drawing.Color>();
                List<float> offsets = new List<float>();

                foreach (var stop in BrushStops.ToList().OrderBy(x => x.OffsetPercent))
                {
                    colors.Add(stop.Color.ToGdiColor());
                    offsets.Add((float)stop.OffsetPercent / 100f);
                }

                blend.Colors = colors.ToArray();
                blend.Positions = offsets.ToArray();

                brush.InterpolationColors = blend;

                return brush;
            }
            else if (BrushStops.Count == 1)
            {
                return new System.Drawing.SolidBrush(BrushStops.First().Color.ToGdiColor());
            }
            else
            {
                return System.Drawing.Brushes.White;
            }
        }

        #endregion

        #region Internal Methods

        /// <summary>
        /// Raises the <see cref="HasOutOfGamutBrushStop"/> property changed event.
        /// </summary>
        internal void RaiseHasOutOfGamutBrushStop()
        {
            RaisePropertyChanged(nameof(HasOutOfGamutBrushStop));
        }

        #endregion

        #region Cloning

        /// <summary>
        /// Clones this segment with its brush stops.
        /// </summary>
        /// <returns></returns>
        public override Segment Clone()
        {
            Segment cloned = base.Clone();

            cloned.BrushStops = BrushStops.Select(x => x.Clone()).ToSynchronizedObservableCollection();

            foreach (var stop in cloned.BrushStops)
            {
                stop.SegmentGuid = cloned.Guid;
                stop.Segment = cloned;
            }

            return cloned;
        }

        /// <summary>
        /// Clones this segment and assigns it to the specified job.
        /// </summary>
        /// <param name="job">The job.</param>
        /// <returns></returns>
        public Segment Clone(Job job)
        {
            Segment cloned = base.Clone();

            cloned.BrushStops = BrushStops.Select(x => x.Clone(cloned)).ToSynchronizedObservableCollection();

            cloned.Job = job;
            cloned.JobGuid = job.Guid;

            return cloned;
        }

        /// <summary>
        /// Clones this segment with its brush stops.
        /// </summary>
        /// <returns></returns>
        ISegment ISegment.Clone()
        {
            return Clone() as ISegment;
        }

        /// <summary>
        /// Clones this segment and assigns it to the specified job.
        /// </summary>
        /// <param name="job">The job.</param>
        /// <returns></returns>
        ISegment ISegment.Clone(Job job)
        {
            return Clone(job) as ISegment;
        }

        #endregion

        #region Delete

        /// <summary>
        /// Removes this entity and all dependent entities from the specified db context.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Delete(ObservablesContext context)
        {
            base.Delete(context);

            if (BrushStops != null && BrushStops.Count > 0)
            {
                context.BrushStops.RemoveRange(BrushStops);
            }

            context.Segments.Remove(this);
        }

        #endregion
    }
}