aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.BL/EntitiesExtensions/Job.cs
blob: 92ba204f2fbf6ea35ff0d437f8cd551eadc09d7a (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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Tango.BL.Attributes;
using Tango.BL.Enumerations;

namespace Tango.BL.Entities
{
    /// <summary>
    /// Extends the standard observable Job class.
    /// </summary>
    /// <seealso cref="Tango.BL.Entities.ObservableEntity{Tango.BL.Entities.Job}" />
    public partial class Job
    {
        private double _lastLength;

        /// <summary>
        /// Initializes a new instance of the <see cref="Job"/> class.
        /// </summary>
        public Job(DateTime creationDate)
        {
            CreationDate = creationDate;
        }

        #region Events

        /// <summary>
        /// Occurs when the job total segments length has changed.
        /// </summary>
        public event EventHandler LengthChanged;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the total job segments length.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public double Length
        {
            get
            {
                _lastLength = GetLength();
                return _lastLength;
            }
        }

        /// <summary>
        /// Gets the total job segments length multiplied by number of units if it is an embroidery job.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public double LengthIncludingNumberOfUnits
        {
            get
            {
                _lastLength = GetLength();
                var l = _lastLength * NumberOfUnits;

                if (EnableInterSegment && NumberOfUnits > 1)
                {
                    l += ((NumberOfUnits - 1) * InterSegmentLength);
                }

                return l;
            }
        }

        /// <summary>
        /// Gets or sets the job <see cref="Status"/> property as <see cref="JobStatus"/> enum instead of int.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public JobStatuses JobStatus
        {
            get { return (JobStatuses)Status; }
            set { Status = value.ToInt32(); RaisePropertyChangedAuto(); RaisePropertyChanged(nameof(JobCategories)); }
        }

        /// <summary>
        /// Gets the collection of <see cref="JobCategories">job categories</see> which is generated by the <see cref="JobStatus"/>.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public List<JobCategories> JobCategories
        {
            get
            {
                return typeof(JobStatuses).GetField(JobStatus.ToString()).GetCustomAttribute<JobStatusAttribute>().Categories;
            }
        }

        /// <summary>
        /// Gets or sets the job <see cref="Type"/> property as <see cref="JobType"/> enum instead of int.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public JobTypes JobType
        {
            get { return (JobTypes)Type; }
            set { Type = value.ToInt32(); RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the job <see cref="SpoolsDistribution"/> property as a <see cref="Boolean"/> property.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public bool IsAllSegmentsPerSpool
        {
            get { return ((SpoolsDistributions)SpoolsDistribution) == SpoolsDistributions.AllSegments; }
            set
            {
                SpoolsDistribution = value ? SpoolsDistributions.AllSegments.ToInt32() : SpoolsDistributions.SingleSegment.ToInt32();
                RaisePropertyChangedAuto();
            }
        }

        /// <summary>
        /// Gets or sets the effective segments.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public ObservableCollection<Segment> EffectiveSegments
        {
            get
            {
                if (EnableInterSegment)
                {
                    ObservableCollection<Segment> effectiveSegments = new ObservableCollection<Segment>();

                    foreach (var s in Segments)
                    {
                        effectiveSegments.Add(s);

                        if (Segments.IndexOf(s) != Segments.Count - 1)
                        {
                            effectiveSegments.Add(CreateInterSegment(InterSegmentLength));
                        }
                    }

                    return effectiveSegments;
                }
                else
                {
                    return Segments;
                }
            }
        }

        /// <summary>
        /// Gets or sets the job fine tuning status.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public FineTuningStatuses JobFineTuningStatus
        {
            get { return (FineTuningStatuses)FineTuningStatus; }
            set { FineTuningStatus = value.ToInt32(); RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the job sample dye status.
        /// </summary>
        [NotMapped]
        [JsonIgnore]
        public SampleDyeStatuses JobSampleDyeStatus
        {
            get { return (SampleDyeStatuses)SampleDyeStatus; }
            set { SampleDyeStatus = value.ToInt32(); RaisePropertyChangedAuto(); }
        }

        private JobDesignations _designation;
        [NotMapped]
        [JsonIgnore]
        public JobDesignations Designation
        {
            get { return _designation; }
            set { _designation = value; RaisePropertyChangedAuto(); }
        }

        [NotMapped]
        [JsonIgnore]
        public EditingStates JobEditingState
        {
            get { return (EditingStates)EditingState; }
            set { EditingState = value.ToInt32(); RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the CollectionChanged event of the Segments collection.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        private void Segments_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            foreach (var segment in Segments)
            {
                segment.PropertyChanged += Segment_PropertyChanged;
            }

            OnLengthChanged();
            RaisePropertyChanged(nameof(EffectiveSegments));
        }

        /// <summary>
        /// Handles the PropertyChanged event of all job segments.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        private void Segment_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(Segment.Length))
            {
                OnLengthChanged();
            }
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the <see cref="Length"/> property has been changed
        /// </summary>
        protected virtual void OnLengthChanged()
        {
            if (_lastLength != GetLength())
            {
                RaisePropertyChanged(nameof(Length));
                RaisePropertyChanged(nameof(LengthIncludingNumberOfUnits));
                LengthChanged?.Invoke(this, new EventArgs());
            }
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Raises the property changed event.
        /// </summary>
        /// <param name="propName">Name of the property.</param>
        protected override void RaisePropertyChanged(string propName)
        {
            base.RaisePropertyChanged(propName);

            if (propName == nameof(Segments))
            {
                if (Segments != null)
                {
                    Segments.CollectionChanged -= Segments_CollectionChanged;
                    Segments.CollectionChanged += Segments_CollectionChanged;

                    OnLengthChanged();
                    RaisePropertyChanged(nameof(EffectiveSegments));
                }
            }

            if (propName == nameof(InterSegmentLength) || propName == nameof(EnableInterSegment))
            {
                OnLengthChanged();
                RaisePropertyChanged(nameof(EffectiveSegments));
            }

            if (propName == nameof(ColorSpace))
            {
                //Make all brush stops the same color space if job color space is not null!
                if (ColorSpace != null)
                {
                    Segments.SelectMany(x => x.BrushStops).ToList().ForEach(x => x.ColorSpace = ColorSpace);
                }
            }

            if (propName == nameof(NumberOfUnits))
            {
                LengthChanged?.Invoke(this, new EventArgs());
            }

            if (propName == nameof(LengthPercentageFactor))
            {
                OnLengthChanged();
                Segments.ToList().ForEach(x => x.RaiseLengthWithFactorChanged());
            }
        }

        public override Job Clone()
        {
            Job cloned = base.Clone();

            cloned.Name = Name + " - Copy";
            cloned.CreationDate = DateTime.UtcNow;
            cloned.LastRun = null;
            cloned.ColorSpace = ColorSpace;
            cloned.Customer = Customer;
            cloned.LastRun = null;
            cloned.Rml = Rml;
            cloned.SpoolType = SpoolType;
            cloned.WindingMethod = WindingMethod;
            cloned.Segments = Segments.Select(x => x.Clone(cloned)).ToObservableCollection();

            foreach (var segment in cloned.Segments)
            {
                segment.JobGuid = cloned.Guid;
                segment.Job = cloned;
            }

            return cloned;
        }

        public override void DefferedDelete(ObservablesContext context)
        {
            Segments.ToList().ForEach(x => x.DefferedDelete(context));
            Segments.Clear();
            base.DefferedDelete(context);
        }

        #endregion

        #region Private Methods

        private double GetLength()
        {
            return Segments.Sum(x => x.LengthWithFactor) + (EnableInterSegment ? (InterSegmentLength * (Segments.Count > 0 ? Segments.Count - 1 : Segments.Count)) : 0);
        }

        #endregion

        #region Public Methods

        public BitmapSource CreateSegmentsPie(double width, double height)
        {
            Bitmap bmp = new Bitmap((int)width, (int)height);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Transparent);
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                int fromAngle = -90;
                double totalLength = Segments.Sum(x => x.Length); //Excluding inter segment.

                foreach (var segment in Segments.OrderBy(x => x.SegmentIndex))
                {
                    int toAngle = (int)((segment.Length / totalLength) * 360d);
                    g.FillPie(segment.CreateGdiBrush(bmp.Width - 2, bmp.Height - 2), new Rectangle(0, 0, bmp.Width - 2, bmp.Height - 2), fromAngle, toAngle);
                    fromAngle += toAngle;
                }
            }

            var source = bmp.ToBitmapSource();
            bmp.Dispose();
            return source;
        }

        /// <summary>
        /// Adds a new solid segment.
        /// </summary>
        public Segment AddSolidSegment()
        {
            return AddSolidSegment(System.Windows.Media.Colors.Black);
        }

        /// <summary>
        /// Adds a new solid segment.
        /// </summary>
        public Segment AddSolidSegment(System.Windows.Media.Color color)
        {
            return AddSolidSegment(color, 10);
        }

        /// <summary>
        /// Adds a new solid segment.
        /// </summary>
        public Segment AddSolidSegment(double length)
        {
            return AddSolidSegment(System.Windows.Media.Colors.Black, length);
        }

        /// <summary>
        /// Adds a new solid segment.
        /// </summary>
        public Segment AddSolidSegment(System.Windows.Media.Color color, double length)
        {
            Segment segment = new Segment();
            segment.Name = "Standard Segment";

            if (Segments.Count > 0)
            {
                segment.SegmentIndex = Segments.Max(x => x.SegmentIndex) + 1;
            }
            else
            {
                segment.SegmentIndex = 1;
            }

            segment.Length = length;

            segment.Job = this;

            var stop = segment.AddBrushStop();
            stop.Color = color;
            Segments.Add(segment);

            return segment;
        }

        /// <summary>
        /// Adds a new gradient segment.
        /// </summary>
        public Segment AddGradientSegment()
        {
            return AddSolidSegment(10);
        }

        /// <summary>
        /// Adds a new gradient segment.
        /// </summary>
        public Segment AddGradientSegment(double length)
        {
            var segment = AddSolidSegment(length);
            segment.BrushStops.Last().Color = System.Windows.Media.Colors.Silver;
            segment.AddBrushStop();
            segment.BrushStops.Last().Color = System.Windows.Media.Colors.DimGray;
            return segment;
        }

        /// <summary>
        /// Gets the duration estimation for this job.
        /// </summary>
        /// <param name="processParameters">The process parameters.</param>
        /// <returns></returns>
        public TimeSpan GetEstimatedDuration(ProcessParametersTable processParameters)
        {
            if (processParameters.DyeingSpeed == 0)
            {
                throw new ArgumentException("Process parameters dying speed cannot be zero.");
            }
            return TimeSpan.FromSeconds((LengthIncludingNumberOfUnits + processParameters.DryerBufferLength) / (processParameters.DyeingSpeed / 100d));
        }

        /// <summary>
        /// Translates the job progress to time.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="processParameters">The process parameters.</param>
        /// <returns></returns>
        public static TimeSpan TranslateProgressToTime(double progress, ProcessParametersTable processParameters)
        {
            return TimeSpan.FromSeconds(progress / (processParameters.DyeingSpeed / 100d));
        }

        /// <summary>
        /// Creates an inter segment.
        /// </summary>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public static Segment CreateInterSegment(double length)
        {
            return new Segment()
            {
                IsInterSegment = true,
                Length = length,
                BrushStops = new ObservableCollection<BrushStop>()
                            {
                                new BrushStop()
                                {
                                     ColorSpace = new ColorSpace(),
                                     Color = System.Windows.Media.Colors.White,
                                }
                            },
            };
        }


        #endregion

        #region Validation

        protected override void OnValidating(ObservablesContext context)
        {
            base.OnValidating(context);

            if (String.IsNullOrWhiteSpace(Name))
            {
                InsertError(nameof(Name), "Job name is required");
            }
        }

        #endregion
    }
}