aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/ViewModels/JobViewVM.cs
blob: 1b80eed35446207153aca3a9662a3e4df826ed32 (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
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.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tango Module")]
[assembly: AssemblyVersion("1.0.0.0")]

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
                                     //(used if a resource is not found in the page,
                                     // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
                                              //(used if a resource is not found in the page,
                                              // app, or any theme specific resource dictionaries)
)]
53'>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 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.PPC.Common;
using Tango.PPC.Jobs.Messages;
using System.Data.Entity;
using Tango.Core.Commands;
using System.Windows;
using Tango.Touch.Controls;
using System.Windows.Media;
using Tango.DragAndDrop;
using System.ComponentModel;
using System.Windows.Data;
using Tango.PPC.Jobs.Dialogs;
using Tango.PPC.Jobs.Views;
using System.Runtime.InteropServices;
using System.Threading;
using Tango.SharedUI.Helpers;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Jobs.NavigationObjects;
using Tango.PPC.Jobs.ViewContracts;
using System.Collections.ObjectModel;
using Tango.PPC.Common.Models;
using Tango.Logging;
using Tango.PPC.Common.Messages;
using Tango.BL.Builders;
using Tango.PPC.Jobs.AppButtons;
using Tango.Core.Threading;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using Tango.Explorer;
using Tango.PPC.Storage;
using System.IO;
using Tango.ColorConversion;
using Tango.Integration.Operation;

namespace Tango.PPC.Jobs.ViewModels
{
    /// <summary>
    /// Represents the selected job view model.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    public class JobViewVM : PPCViewModel<IJobView>, INavigationObjectReceiver<JobNavigationObject>
    {
        private ObservablesContext _db;
        private bool _can_navigate_back;
        private Thread _check_gamut_thread;
        private Job _job_to_load;
        private JobNavigationIntent _job_to_load_intent;
        private static Dictionary<String, List<FineTuneItem>> _jobs_fine_tune_items;
        private StartPrintingButton _start_printing_btn;
        private ActionTimer _volumeConversionTimer;
        private IColorConverter _converter;
        private string _current_job_string;

        #region Properties

        private Job _job;
        /// <summary>
        /// Gets or sets the selected job.
        /// </summary>
        public Job Job
        {
            get { return _job; }
            set { _job = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _segmentsCollectionView;
        /// <summary>
        /// Gets or sets the job segments collection view.
        /// </summary>
        public ICollectionView SegmentsCollectionView
        {
            get { return _segmentsCollectionView; }
            set
            {
                _segmentsCollectionView = value;
                RaisePropertyChangedAuto();
            }
        }

        private List<ColorSpace> _colorSpaces;
        /// <summary>
        /// Gets or sets the available color spaces.
        /// </summary>
        public List<ColorSpace> ColorSpaces
        {
            get { return _colorSpaces; }
            set { _colorSpaces = value; RaisePropertyChangedAuto(); }
        }

        private List<Rml> _rmls;
        /// <summary>
        /// Gets or sets the available RMLS.
        /// </summary>
        public List<Rml> Rmls
        {
            get { return _rmls; }
            set { _rmls = value; RaisePropertyChangedAuto(); }
        }

        private List<SpoolType> _spoolTypes;
        /// <summary>
        /// Gets or sets the available spool types.
        /// </summary>
        public List<SpoolType> SpoolTypes
        {
            get { return _spoolTypes; }
            set { _spoolTypes = value; RaisePropertyChangedAuto(); }
        }

        private List<Customer> _customers;
        /// <summary>
        /// Gets or sets the available customers.
        /// </summary>
        public List<Customer> Customers
        {
            get { return _customers; }
            set { _customers = value; RaisePropertyChangedAuto(); }
        }

        private String _customersFilter;
        /// <summary>
        /// Gets or sets the customers filter.
        /// </summary>
        public String CustomersFilter
        {
            get { return _customersFilter; }
            set { _customersFilter = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the customers automatic complete provider.
        /// </summary>
        public AutoCompleteProvider<Customer> CustomersAutoCompleteProvider { get; set; }

        private ObservableCollection<FineTuneItem> _fineTuneItems;
        /// <summary>
        /// Gets or sets the fine tune items.
        /// </summary>
        public ObservableCollection<FineTuneItem> FineTuneItems
        {
            get { return _fineTuneItems; }
            set { _fineTuneItems = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<FineTuneItem> _approvalFineTuneItems;
        /// <summary>
        /// Gets or sets the fine tune items.
        /// </summary>
        public ObservableCollection<FineTuneItem> ApprovalFineTuneItems
        {
            get { return _approvalFineTuneItems; }
            set { _approvalFineTuneItems = value; RaisePropertyChangedAuto(); }
        }

        private bool _isFineTuneExpanded;
        /// <summary>
        /// Gets or sets a value indicating whether the fine tuning region is expanded.
        /// </summary>
        public bool IsFineTuneExpanded
        {
            get { return _isFineTuneExpanded; }
            set
            {
                _isFineTuneExpanded = value;
                RaisePropertyChangedAuto();

                if (_isFineTuneExpanded)
                {
                    SyncFineTuneItemsToBrushStops();
                }
            }
        }

        private bool _isJobDetailsExpanded;
        /// <summary>
        /// Gets or sets a value indicating whether the job details area is expanded.
        /// </summary>
        public bool IsJobDetailsExpanded
        {
            get { return _isJobDetailsExpanded; }
            set { _isJobDetailsExpanded = value; RaisePropertyChangedAuto(); }
        }

        private List<ColorCatalogsItem> _catalogItems;
        /// <summary>
        /// Gets or sets the twine catalog items.
        /// </summary>
        public List<ColorCatalogsItem> CatalogItems
        {
            get { return _catalogItems; }
            set { _catalogItems = value; RaisePropertyChangedAuto(); }
        }

        private ColorCatalogsItem _selectedCatalogItem;
        /// <summary>
        /// Gets or sets the selected catalog item.
        /// </summary>
        public ColorCatalogsItem SelectedCatalogItem
        {
            get { return _selectedCatalogItem; }
            set { _selectedCatalogItem = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the twine catalog automatic complete provider.
        /// </summary>
        public IAutoCompleteProvider CatalogAutoCompleteProvider { get; set; }

        private ColorCatalog _selectedCatalog;
        /// <summary>
        /// Gets or sets the selected catalog.
        /// </summary>
        public ColorCatalog SelectedCatalog
        {
            get { return _selectedCatalog; }
            set { _selectedCatalog = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the add solid segment command.
        /// </summary>
        public RelayCommand AddSolidSegmentCommand { get; set; }

        /// <summary>
        /// Gets or sets the add gradient segment command.
        /// </summary>
        public RelayCommand AddGradientSegmentCommand { get; set; }

        /// <summary>
        /// Gets or sets the add brush stop command.
        /// </summary>
        public RelayCommand<Segment> AddBrushStopCommand { get; set; }

        /// <summary>
        /// Gets or sets the segment dropped command.
        /// </summary>
        public RelayCommand<DropEventArgs> SegmentDroppedCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove segment command.
        /// </summary>
        public RelayCommand<Segment> RemoveSegmentCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove brush stop command.
        /// </summary>
        public RelayCommand<BrushStop> RemoveBrushStopCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove job command.
        /// </summary>
        public RelayCommand RemoveJobCommand { get; set; }

        /// <summary>
        /// Gets or sets the save job command.
        /// </summary>
        public RelayCommand SaveJobCommand { get; set; }

        /// <summary>
        /// Gets or sets the replace brush stop command.
        /// </summary>
        public RelayCommand<BrushStop> ReplaceBrushStopCommand { get; set; }

        /// <summary>
        /// Gets or sets the twine catalog field tap command.
        /// </summary>
        public RelayCommand<BrushStop> OpenCatalogCommand { get; set; }

        /// <summary>
        /// Gets or sets the increase decrease samples to dye command.
        /// </summary>
        public RelayCommand<String> IncreaseDecreaseSamplesToDyeCommand { get; set; }

        /// <summary>
        /// Gets or sets the start sample dye command.
        /// </summary>
        public RelayCommand StartSampleDyeCommand { get; set; }

        /// <summary>
        /// Gets or sets the dye command.
        /// </summary>
        public RelayCommand DyeCommand { get; set; }

        /// <summary>
        /// Gets or sets the approve sample command.
        /// </summary>
        public RelayCommand ApproveSampleCommand { get; set; }

        /// <summary>
        /// Gets or sets the repeat sample dye command.
        /// </summary>
        public RelayCommand RepeatSampleDyeCommand { get; set; }

        /// <summary>
        /// Gets or sets another sample command.
        /// </summary>
        public RelayCommand AnotherSampleCommand { get; set; }

        /// <summary>
        /// Gets or sets the invoke fine tuning palette command.
        /// </summary>
        public RelayCommand<FineTuneItem> InvokeFineTuningPaletteCommand { get; set; }

        /// <summary>
        /// Gets or sets the reset fine tuning command.
        /// </summary>
        public RelayCommand ResetFineTuningCommand { get; set; }

        /// <summary>
        /// Gets or sets the start fine tuning command.
        /// </summary>
        public RelayCommand StartFineTuningCommand { get; set; }

        /// <summary>
        /// Gets or sets the approve fine tuning command.
        /// </summary>
        public RelayCommand ApproveFineTuningCommand { get; set; }

        /// <summary>
        /// Gets or sets the repeat fine tuning command.
        /// </summary>
        public RelayCommand RepeatFineTuningCommand { get; set; }

        /// <summary>
        /// Gets or sets the export embroidery command.
        /// </summary>
        public RelayCommand ExportEmbroideryCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes the <see cref="JobViewVM"/> class.
        /// </summary>
        static JobViewVM()
        {
            _jobs_fine_tune_items = new Dictionary<string, List<FineTuneItem>>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="JobViewVM"/> class.
        /// </summary>
        public JobViewVM()
        {
            _converter = new DefaultColorConverter();

            _volumeConversionTimer = new ActionTimer(TimeSpan.FromMilliseconds(50));

            RegisterForMessage<JobSelectedMessage>(HandleJobSelectedMessage);

            FineTuneItems = new ObservableCollection<FineTuneItem>();
            ApprovalFineTuneItems = new ObservableCollection<FineTuneItem>();
            CatalogItems = new List<ColorCatalogsItem>();

            CustomersAutoCompleteProvider = new AutoCompleteProvider<Customer>((customer, filter) =>
            {
                return customer.Name.ToLower().StartsWith(filter != null ? filter.ToLower() : String.Empty);
            });


            CatalogAutoCompleteProvider = new AutoCompleteProvider<ColorCatalogsItem>((item, filter) =>
            {
                return !String.IsNullOrWhiteSpace(filter) && item.Name.ToLower().StartsWith(filter.ToLower());
            });

            //Initialize Commands
            AddSolidSegmentCommand = new RelayCommand(() => AddSolidSegment());
            AddBrushStopCommand = new RelayCommand<Segment>(AddBrushStop);
            AddGradientSegmentCommand = new RelayCommand(() => AddGradientSegment());
            SegmentDroppedCommand = new RelayCommand<DropEventArgs>((e) =>
            {
                DragAndDropSegment(
                    (e.Draggable as FrameworkElement).DataContext as Segment,
                    (e.Droppable as FrameworkElement).DataContext as Segment);
            });

            RemoveSegmentCommand = new RelayCommand<Segment>(RemoveSegment);
            RemoveBrushStopCommand = new RelayCommand<BrushStop>(RemoveBrushStop);
            RemoveJobCommand = new RelayCommand(RemoveJob);
            SaveJobCommand = new RelayCommand(() => SaveJob());
            ReplaceBrushStopCommand = new RelayCommand<BrushStop>(InvokeColorAdjustmentForBrushStop);
            IncreaseDecreaseSamplesToDyeCommand = new RelayCommand<string>((x) =>
            {
                if (x == "+")
                {
                    Job.SampleUnitsOrMeters++;
                }
                else
                {
                    Job.SampleUnitsOrMeters--;
                }
            });

            _check_gamut_thread = new Thread(CheckGamutThreadMethod);
            _check_gamut_thread.IsBackground = true;

            StartSampleDyeCommand = new RelayCommand(StartSampleDye, CanStartJob);
            DyeCommand = new RelayCommand(StartJob, CanStartJob);

            ApproveSampleCommand = new RelayCommand(ApproveSampleDye);
            RepeatSampleDyeCommand = new RelayCommand(RepeatSampleDye);
            AnotherSampleCommand = new RelayCommand(DyeAnotherSample);
            InvokeFineTuningPaletteCommand = new RelayCommand<FineTuneItem>(InvokeFineTuningPalette);
            ResetFineTuningCommand = new RelayCommand(() => ResetFineTuning(true));
            StartFineTuningCommand = new RelayCommand(StartFineTuning, () => FineTuneItems.Any(x => x.IsSelected) && CanStartJob());
            RepeatFineTuningCommand = new RelayCommand(RepeatFineTuning);
            ApproveFineTuningCommand = new RelayCommand(ApproveFineTuning);
            OpenCatalogCommand = new RelayCommand<BrushStop>(OpenCatalog);
            ExportEmbroideryCommand = new RelayCommand(ExportEmbroidery);
        }

        #endregion

        #region Job Management

        /// <summary>
        /// Loads the job.
        /// </summary>
        private async void LoadJob()
        {
            try
            {
                if (!(_job_to_load == null || (_job_to_load != null && Job != null && _job_to_load.Guid == Job.Guid)))
                {
                    View.ScrollToTop();

                    LogManager.Log($"Loading selected job '{_job_to_load.Name}'...");

                    //NotificationProvider.SetGlobalBusyMessage("Loading job details...");
                    IsFree = false;

                    _can_navigate_back = false;

                    if (_db != null)
                    {
                        Rmls.ForEach(x => x.Cct = null);
                        Rmls = null;
                        _db.Dispose();
                        GC.Collect();
                    }

                    _db = ObservablesContext.CreateDefault();

                    Job = await new JobBuilder(_db).Set(_job_to_load.Guid)
                        .WithConfiguration()
                        .WithRML()
                        .WithUser()
                        .WithSegments()
                        .WithBrushStops()
                        .BuildAsync();

                    Job.RmlChanged -= OnRmlChanged;
                    Job.RmlChanged += OnRmlChanged;
                    Job.NameChanged -= Job_NameChanged;
                    Job.NameChanged += Job_NameChanged;

                    Job.ValidateOnPropertyChanged = true;

                    LogManager.Log("Loading RMLS...");
                    Rmls = (await new RmlsCollectionBuilder(_db).SetAll().WithActiveParametersGroup().WithCAT(Job.MachineGuid).WithCCT().WithLiquidFactors().ForSite(MachineProvider.Machine.SiteGuid).BuildAsync()).ToList();
                    LogManager.Log("Loading Color Spaces...");
                    ColorSpaces = await _db.ColorSpaces.ToListAsync();
                    LogManager.Log("Loading Spool Types...");
                    SpoolTypes = await _db.SpoolTypes.ToListAsync();
                    LogManager.Log("Loading Customers...");
                    Customers = await _db.Customers.Where(x => x.OrganizationGuid == MachineProvider.Machine.OrganizationGuid).ToListAsync();

                    if (Job.ColorSpace.Space == BL.Enumerations.ColorSpaces.Catalog)
                    {
                        SelectedCatalog = await new CatalogBuilder(_db).Set(Job.ColorCatalogGuid).WithGroups().WithItems().BuildAsync();

                        if (SelectedCatalog != null)
                        {
                            CatalogItems = SelectedCatalog.ColorCatalogsGroups.SelectMany(x => x.ColorCatalogsItems).OrderBy(x => x.ItemIndex).ToList();
                        }
                        else
                        {
                            await NotificationProvider.ShowError("The selected color catalog for this job could not be found.\nCannot load job.");
                            Job = null;
                            _can_navigate_back = true;
                            await NavigationManager.NavigateBack();
                            return;
                        }
                    }

                    foreach (var segment in Job.Segments)
                    {
                        SetSegmentLiquidVolumesIfVolume(segment);
                    }

                    if (!_check_gamut_thread.IsAlive)
                    {
                        _check_gamut_thread.Start();
                    }

                    SegmentsCollectionView = CollectionViewSource.GetDefaultView(Job.Segments);
                    SegmentsCollectionView.SortDescriptions.Add(new SortDescription(nameof(Segment.SegmentIndex), ListSortDirection.Ascending));

                    ResetFineTuning();

                    _job_to_load = null;

                    _current_job_string = Job.ToJobFileWhenLoaded().ToString();
                }

                if (!_jobs_fine_tune_items.ContainsKey(Job.Guid) && Job.JobFineTuningStatus == BL.Enumerations.FineTuningStatuses.PendingApproval)
                {
                    Job.JobFineTuningStatus = BL.Enumerations.FineTuningStatuses.Unspecified;
                }

                if (_job_to_load_intent == JobNavigationIntent.NewJob)
                {
                    IsJobDetailsExpanded = true;
                }

                LogManager.Log($"Job editing state = '{Job.JobEditingState}'.");

                if (Job.JobEditingState == BL.Enumerations.EditingStates.SampleDye && Job.JobSampleDyeStatus == BL.Enumerations.SampleDyeStatuses.PendingApproval)
                {
                    LogManager.Log("Directing view to display sample dye region.");
                    View.DisplaySampleDye();
                }
                else if (Job.JobEditingState == BL.Enumerations.EditingStates.FineTuning && Job.JobFineTuningStatus == BL.Enumerations.FineTuningStatuses.PendingApproval)
                {
                    LogManager.Log("Directing view to display fine tuning region.");
                    View.DisplayFineTuning();
                }

                ValidateBrushStops();

                DyeCommand.RaiseCanExecuteChanged();
                StartSampleDyeCommand.RaiseCanExecuteChanged();
                StartFineTuningCommand.RaiseCanExecuteChanged();
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error loading job '{_job_to_load.Name}'");
                await NotificationProvider.ShowError("An error occurred while trying to load the selected job.");
                _can_navigate_back = true;
                await NavigationManager.NavigateBack();
            }
            finally
            {
                InvokeUI(() =>
                {
                    IsFree = true;
                    //NotificationProvider.ReleaseGlobalBusyMessage();
                });
            }
        }

        private void Job_NameChanged(object sender, string e)
        {
            DyeCommand.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Saves the job.
        /// </summary>
        private async void SaveJob(bool displayNotification = true)
        {
            try
            {
                if (Job.Validate(_db))
                {
                    LogManager.Log("Saving job...");

                    if (!String.IsNullOrWhiteSpace(CustomersFilter))
                    {
                        if (!Customers.Exists(x => x.Name == CustomersFilter))
                        {
                            var newCustomer = new Customer()
                            {
                                OrganizationGuid = MachineProvider.Machine.OrganizationGuid,
                                Name = CustomersFilter,
                            };

                            _db.Customers.Add(newCustomer);

                            Job.Customer = newCustomer;
                        }
                    }

                    Job.LastUpdated = DateTime.UtcNow;
                    Job.IsSynchronized = false;
                    Job.JobStatus = BL.Enumerations.JobStatuses.Draft;
                    Job.MarkModified(_db);
                    await _db.SaveChangesAsync();
                    _current_job_string = Job.ToJobFileWhenLoaded().ToString();

                    if (displayNotification)
                    {
                        await NotificationProvider.ShowInfo(String.Format("Job '{0}' saved successfully.", Job.Name));
                    }

                    RaiseMessage(new JobSavedMessage() { Job = Job });
                }
                else
                {
                    await NotificationProvider.ShowError($"Error saving job. {Job.ValidationErrors.FirstOrDefault()}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error saving job '{Job.Name}'.");
                await NotificationProvider.ShowError("An error occurred while trying to save the job.");
            }
        }

        /// <summary>
        /// Removes the job.
        /// </summary>
        private async void RemoveJob()
        {
            try
            {
                LogManager.Log("Removing job...");

                if (await NotificationProvider.ShowQuestion("Are you sure you want to delete the this job?"))
                {
                    await Job.DeleteCascadeAsync(_db);
                    RaiseMessage(new JobRemovedMessage() { Job = Job });
                    _can_navigate_back = true;
                    await NavigationManager.NavigateBack();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error removing job '{Job.Name}'.");
                await NotificationProvider.ShowError("An error occurred while trying to remove the job.");
            }
        }

        /// <summary>
        /// Starts the job.
        /// </summary>
        private async void StartJob()
        {
            try
            {
                LogManager.Log("Start job command pressed. Starting job and navigating to job progress view...");
                var handler = await PrintingManager.Print(Job, _db);
                await NavigationManager.NavigateTo<JobsModule>(nameof(JobProgressView));
            }
            catch (InsufficientLiquidQuantityException)
            {
                //Ignore..
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Could not start the current job.");
                await NotificationProvider.ShowError($"{ex.Message}.");
            }
        }

        /// <summary>
        /// Determines whether this instance [can start job].
        /// </summary>
        private bool CanStartJob()
        {
            return
                Job != null && Job.Validate(_db) &&
                !Job.Segments.SelectMany(x => x.BrushStops).Where(x => !x.IsTransparent).ToList().Exists(x => x.IsOutOfGamut);
        }

        #endregion

        #region RML Changed

        protected virtual void OnRmlChanged(object sender, Rml rml)
        {
            //There is no need for that.

            ////Replace all brush stops twine color catalogs.
            //foreach (var stop in Job.Segments.SelectMany(x => x.BrushStops).Where(x => x.ColorCatalog != null && x.BrushColorSpace == BL.Enumerations.ColorSpaces.Twine).ToList())
            //{
            //    var replacement = CatalogItems.SingleOrDefault(x => x.Name == stop.ColorCatalog.Name);
            //    stop.ColorCatalog = replacement;
            //}

            ////Replace all brush stops coats color catalogs.
            //foreach (var stop in Job.Segments.SelectMany(x => x.BrushStops).Where(x => x.ColorCatalog != null && x.BrushColorSpace == BL.Enumerations.ColorSpaces.Coats).ToList())
            //{
            //    var replacement = CoatsCatalogItems.SingleOrDefault(x => x.Name == stop.ColorCatalog.Name);
            //    stop.ColorCatalog = replacement;
            //}

            ResetFineTuning();
        }

        #endregion

        #region Segments Management

        /// <summary>
        /// Adds a new solid segment.
        /// </summary>
        private Segment AddSolidSegment()
        {
            try
            {
                LogManager.Log("Adding new solid segment...");
                var s = Job.AddSolidSegment(Settings.DefaultSegmentLength > 0 ? Settings.DefaultSegmentLength : 10);
                SetSegmentLiquidVolumesIfVolume(s);
                return s;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Could not add a new solid segment.");
                NotificationProvider.ShowError("An error occurred while trying to add a new segment.");
                return null;
            }
        }

        /// <summary>
        /// Adds a new gradient segment.
        /// </summary>
        private Segment AddGradientSegment()
        {
            try
            {
                LogManager.Log("Adding new gradient segment...");
                var s = Job.AddGradientSegment(Settings.DefaultSegmentLength > 0 ? Settings.DefaultSegmentLength : 10);
                SetSegmentLiquidVolumesIfVolume(s);
                return s;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Could not add a new gradient segment.");
                NotificationProvider.ShowError("An error occurred while trying to add a new segment.");
                return null;
            }
        }

        /// <summary>
        /// Called when a segment has been dragged and dropped into another segment.
        /// </summary>
        /// <param name="draggedJob">The dragged job.</param>
        /// <param name="droppedJob">The dropped job.</param>
        private void DragAndDropSegment(Segment draggedSegment, Segment droppedSegment)
        {
            LogManager.Log($"Segment Drag & Drop '{draggedSegment.SegmentIndex}' => '{droppedSegment.SegmentIndex}'.");

            if (draggedSegment.SegmentIndex > droppedSegment.SegmentIndex)
            {
                draggedSegment.SegmentIndex = droppedSegment.SegmentIndex - 1;
            }
            else
            {
                draggedSegment.SegmentIndex = droppedSegment.SegmentIndex + 1;
            }

            int index = 1;

            foreach (var segment in Job.Segments.OrderBy(x => x.SegmentIndex))
            {
                segment.SegmentIndex = index++;
            }

            SegmentsCollectionView.Refresh();
        }

        /// <summary>
        /// Removes the segment.
        /// </summary>
        /// <param name="segment">The segment.</param>
        private async void RemoveSegment(Segment segment)
        {
            if (Job.Segments.Count > 1)
            {
                try
                {
                    if (await NotificationProvider.ShowQuestion("Are you sure you want to remove the selected segment?"))
                    {
                        LogManager.Log($"Removing job segment {segment.SegmentIndex}");

                        segment.BrushStops.ToList().ForEach(x =>
                        {
                            _db.BrushStops.Remove(x);
                        });
                        _db.Segments.Remove(segment);

                        ArrangeSegmentsIndices();

                        DyeCommand.RaiseCanExecuteChanged();
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Could not remove segment.");
                    await NotificationProvider.ShowError("An error occurred while trying to add a new segment.");
                }
            }
            else
            {
                await NotificationProvider.ShowInfo("A job must contain at least one color segment.");
            }
        }

        /// <summary>
        /// Sets the segment liquid volumes.
        /// </summary>
        /// <param name="segment">The segment.</param>
        private void SetSegmentLiquidVolumesIfVolume(Segment segment)
        {
            if (Job.ColorSpace.Code == BL.Enumerations.ColorSpaces.Volume.ToInt32())
            {
                foreach (var stop in segment.BrushStops)
                {
                    stop.SetLiquidVolumes(Job.Machine.Configuration, Job.Rml, Job.Rml.GetActiveProcessGroup().ProcessParametersTables.FirstOrDefault());

                    var lub = stop.LiquidVolumes.FirstOrDefault(x => x.IdsPack.LiquidType.Code == (int)BL.Enumerations.LiquidTypes.Lubricant);
                    if (lub != null)
                    {
                        lub.Volume = 100;
                    }
                }
            }
        }

        private void ArrangeSegmentsIndices()
        {
            for (int i = 0; i < Job.Segments.Count; i++)
            {
                Job.Segments[i].SegmentIndex = i + 1;
            }
        }

        #endregion

        #region Brush Stops Management

        /// <summary>
        /// Adds a new brush stop to the specified segment.
        /// </summary>
        /// <param name="segment">The segment.</param>
        private void AddBrushStop(Segment segment)
        {
            LogManager.Log($"Adding new brush stop to segment {segment.SegmentIndex}.");
            segment.AddBrushStop();
            SetSegmentLiquidVolumesIfVolume(segment);
        }

        /// <summary>
        /// Removes the brush stop.
        /// </summary>
        /// <param name="brushStop">The brush stop.</param>
        private void RemoveBrushStop(BrushStop brushStop)
        {
            if (brushStop.Segment.BrushStops.Count > 2)
            {
                LogManager.Log($"removing brush stop {brushStop.StopIndex} from segment {brushStop.Segment.SegmentIndex}.");
                var segment = brushStop.Segment;
                _db.BrushStops.Remove(brushStop);
                ArrangeBrushStopsIndices(segment);
            }
            else
            {
                NotificationProvider.ShowInfo("Gradient segments must contain at least two colors.");
            }
        }

        /// <summary>
        /// Invokes the color adjustment for the specified brush stop.
        /// </summary>
        /// <param name="brushStop">The brush stop.</param>
        private async void InvokeColorAdjustmentForBrushStop(BrushStop brushStop)
        {
            try
            {
                LogManager.Log($"Invoking triplet color adjustment dialog for brush stop {brushStop.StopIndex} at segment {brushStop.Segment.SegmentIndex}.");

                LogManager.Log("Retrieving color conversion suggestions for brush stop...");
                PMR.ColorLab.ConversionOutput conversionOutput = null;

                if (brushStop.IsOutOfGamut)
                {
                    conversionOutput = _converter.Convert(brushStop, false);
                }

                BasicColorCorrectionViewVM vm = null;
                List<ColorConversionSuggestion> suggestions = null;

                if (brushStop.IsOutOfGamut)
                {
                    vm = await NotificationProvider.ShowDialog<BasicColorCorrectionViewVM>(new BasicColorCorrectionViewVM()
                    {
                        InvalidBrushStop = brushStop,
                        Suggestions = new List<ColorConversionSuggestion>() { new ColorConversionSuggestion(conversionOutput.SingleCoordinates, 0, 0) },
                    });
                }

                if (vm == null || vm.Result == BasicColorCorrectionViewVM.ColorCorrectionDialogResult.MoreOptions)
                {
                    NotificationProvider.SetGlobalBusyMessage("Generating color hive...");

                    await Task.Factory.StartNew(() =>
                    {
                        conversionOutput = _converter.Convert(brushStop, true);

                        suggestions = conversionOutput.CreateHiveSuggestions();

                        if (vm == null)
                        {
                            var center = suggestions.GetCenterSuggestion();
                            center.Coordinates.Red = brushStop.Red;
                            center.Coordinates.Green = brushStop.Green;
                            center.Coordinates.Blue = brushStop.Blue;

                            center.Coordinates.L = brushStop.L;
                            center.Coordinates.A = brushStop.A;
                            center.Coordinates.B = brushStop.B;
                        }
                    });

                    NotificationProvider.ReleaseGlobalBusyMessage();
                    LogManager.Log("Invoking hive color conversion dialog...");
                    vm = await NotificationProvider.ShowDialog<AdvancedColorCorrectionViewVM>(new AdvancedColorCorrectionViewVM()
                    {
                        InvalidBrushStop = brushStop,
                        Suggestions = suggestions,
                        IsOutOfGamut = brushStop.IsOutOfGamut,
                    });
                }

                if (vm.Result == BasicColorCorrectionViewVM.ColorCorrectionDialogResult.Confirmed)
                {
                    LogManager.Log($"Color suggestion selected: {vm.SelectedSuggestion.Color.ToString()}.");

                    if (brushStop.BrushColorSpace == BL.Enumerations.ColorSpaces.RGB)
                    {
                        brushStop.Red = vm.SelectedSuggestion.Coordinates.Red;
                        brushStop.Green = vm.SelectedSuggestion.Coordinates.Green;
                        brushStop.Blue = vm.SelectedSuggestion.Coordinates.Blue;
                    }
                    else if (brushStop.BrushColorSpace == BL.Enumerations.ColorSpaces.LAB)
                    {
                        brushStop.L = vm.SelectedSuggestion.Coordinates.L;
                        brushStop.A = vm.SelectedSuggestion.Coordinates.A;
                        brushStop.B = vm.SelectedSuggestion.Coordinates.B;
                    }
                    else if (brushStop.BrushColorSpace == BL.Enumerations.ColorSpaces.Volume)
                    {
                        if (vm.SelectedSuggestion != suggestions.GetCenterSuggestion())
                        {
                            vm.SelectedSuggestion.ApplyOnBrushStop(brushStop);
                        }
                    }

                    brushStop.Corrected = true;
                    brushStop.IsOutOfGamut = false;
                    brushStop.OutOfGamutChecked = true;
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error while invoking color adjustment dialog.");
                await NotificationProvider.ShowError("An error occurred while trying to convert the selected color.");
            }
            finally
            {
                NotificationProvider.ReleaseGlobalBusyMessage();
                DyeCommand.RaiseCanExecuteChanged();
            }
        }

        /// <summary>
        /// Called when the brush stop field value has been changed (This called from the view!).
        /// </summary>
        /// <param name="stop">The brush stop.</param>
        [HandleProcessCorruptedStateExceptions]
        public void OnBrushStopFieldValueChanged(BrushStop stop)
        {
            if (stop != null)
            {
                stop.Corrected = false;
                stop.OutOfGamutChecked = false;

                if (stop.BrushColorSpace == BL.Enumerations.ColorSpaces.Volume)
                {
                    _volumeConversionTimer.ResetReplace(() =>
                    {
                        try
                        {
                            var output = _converter.Convert(stop, false);

                            stop.Red = output.SingleCoordinates.Red;
                            stop.Green = output.SingleCoordinates.Green;
                            stop.Blue = output.SingleCoordinates.Blue;
                            stop.Corrected = true;
                            stop.IsOutOfGamut = false;
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "An error occurred while trying to get volume => RGB from conversion engine.");
                        }
                    });
                }
            }
        }

        /// <summary>
        /// Opens the twine catalog for the specified brush stop.
        /// </summary>
        /// <param name="stop">The stop.</param>
        private async void OpenCatalog(BrushStop stop)
        {
            var catalogItem = await NavigationManager.NavigateForResult<JobsModule, TwineCatalogView, ColorCatalogsItem, TwineCatalogNavigationObject>(new TwineCatalogNavigationObject()
            {
                SelectedItem = stop.ColorCatalogsItem,
                Catalog = SelectedCatalog
            }, true);

            if (catalogItem != null)
            {
                stop.ColorCatalogsItem = catalogItem;
            }
        }

        private void ArrangeBrushStopsIndices(Segment segment)
        {
            for (int i = 0; i < segment.BrushStops.Count; i++)
            {
                segment.BrushStops[i].StopIndex = i + 1;
            }
        }

        private bool ValidateBrushStops()
        {
            return Job.Segments.SelectMany(x => x.BrushStops).ToList().All(x => x.Validate(_db));
        }

        #endregion

        #region Job Selection Message

        /// <summary>
        /// Handles the job selected message.
        /// </summary>
        /// <param name="message">The message.</param>
        private void HandleJobSelectedMessage(JobSelectedMessage message)
        {
            _job_to_load = message.Job;
        }

        #endregion

        #region Sample Dye

        /// <summary>
        /// Starts a sample dye.
        /// </summary>
        private async void StartSampleDye()
        {
            try
            {
                LogManager.Log("Sample dye command pressed...");

                await PrintingManager.PrintSample(Job, _db);

                await NavigationManager.NavigateTo<JobsModule>(nameof(JobProgressView));
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error executing sample dye for job {Job.Name}.");
                await NotificationProvider.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// Sets the job status back to not approved.
        /// </summary>
        private void RepeatSampleDye()
        {
            LogManager.Log("Repeat sample dye command pressed...");
            Job.JobEditingState = BL.Enumerations.EditingStates.Default;
            Job.JobSampleDyeStatus = BL.Enumerations.SampleDyeStatuses.Unspecified;
        }

        /// <summary>
        /// Approves the sample dye.
        /// </summary>
        private void ApproveSampleDye()
        {
            LogManager.Log("Approve sample dye command pressed...");

            Job.JobEditingState = BL.Enumerations.EditingStates.Default;
            Job.JobSampleDyeStatus = BL.Enumerations.SampleDyeStatuses.Approved;

            Job.SampleDyeApproveDate = DateTime.UtcNow;
            SaveJob(false);
        }

        /// <summary>
        /// Dyes another sample.
        /// </summary>
        private void DyeAnotherSample()
        {
            LogManager.Log("Dye another sample dye command pressed...");

            Job.JobEditingState = BL.Enumerations.EditingStates.Default;
            Job.JobSampleDyeStatus = BL.Enumerations.SampleDyeStatuses.Unspecified;
        }

        #endregion

        #region Fine Tuning

        /// <summary>
        /// Synchronizes the fine tune items to brush stops.
        /// </summary>
        private async void SyncFineTuneItemsToBrushStops(bool displayBusy = false)
        {
            try
            {
                if (Job != null)
                {
                    if (_jobs_fine_tune_items.ContainsKey(Job.Guid))
                    {
                        FineTuneItems = _jobs_fine_tune_items[Job.Guid].ToObservableCollection();
                    }
                    else
                    {
                        if (displayBusy)
                        {
                            NotificationProvider.SetGlobalBusyMessage("Generating suggestions...");
                        }

                        FineTuneItems.Clear();

                        foreach (var stop in Job.Segments.SelectMany(x => x.BrushStops).Where(x => !x.IsTransparent).Where(x => x.ColorSpace.Space == BL.Enumerations.ColorSpaces.RGB || x.ColorSpace.Space == BL.Enumerations.ColorSpaces.LAB).DistinctBy(x => x.Color))
                        {
                            var conversionoutput = await _converter.ConvertAsync(stop, true);
                            FineTuneItem item = new FineTuneItem(conversionoutput);
                            item.BrushStop = stop;
                            item.BrushStops = Job.Segments.SelectMany(x => x.BrushStops).Where(x => x.Color == stop.Color).ToList();
                            item.SelectedSuggestion = item.Suggestions.GetCenterSuggestion();
                            item.SelectedChanged += () => StartFineTuningCommand.RaiseCanExecuteChanged();
                            FineTuneItems.Add(item);
                        }

                        _jobs_fine_tune_items[Job.Guid] = FineTuneItems.ToList();

                        NotificationProvider.ReleaseGlobalBusyMessage();
                    }

                    ApprovalFineTuneItems = FineTuneItems.Where(x => x.IsSelected).ToObservableCollection();

                    StartFineTuningCommand.RaiseCanExecuteChanged();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error while trying to synchronize fine tuning items with brush stops.");
            }
            finally
            {
                NotificationProvider.ReleaseGlobalBusyMessage();
            }
        }

        /// <summary>
        /// Invokes the fine tuning palette dialog.
        /// </summary>
        /// <param name="fineTuneItem">The fine tune item.</param>
        private async void InvokeFineTuningPalette(FineTuneItem fineTuneItem)
        {
            LogManager.Log("Invoke fine tuning palette command pressed...");

            try
            {
                FineTuningPaletteViewVM vm = new FineTuningPaletteViewVM(fineTuneItem, Job);
                await NotificationProvider.ShowDialog(vm);

                if (vm.DialogResult)
                {
                    fineTuneItem.Suggestions = vm.Suggestions;
                    fineTuneItem.SelectedSuggestion = vm.SelectedSuggestion;
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error invoking the fine tunning palette");
                await NotificationProvider.ShowError("An error occurred while trying to display the fine tunning palette.");
            }
            finally
            {
                NotificationProvider.ReleaseGlobalBusyMessage();
            }
        }

        /// <summary>
        /// Resets the fine tuning.
        /// </summary>
        private void ResetFineTuning(bool displayBusy = false)
        {
            if (Job != null && _jobs_fine_tune_items.ContainsKey(Job.Guid))
            {
                _jobs_fine_tune_items.Remove(Job.Guid);
            }

            SyncFineTuneItemsToBrushStops(displayBusy);
        }

        /// <summary>
        /// Starts the fine tuning.
        /// </summary>
        private async void StartFineTuning()
        {
            try
            {
                LogManager.Log("Start fine tunning job command pressed...");

                _jobs_fine_tune_items[Job.Guid] = FineTuneItems.ToList();

                await PrintingManager.PrintFineTuning(Job, _db, FineTuneItems);

                await NavigationManager.NavigateTo<JobsModule>(nameof(JobProgressView));
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error executing fine tuning job.");
                await NotificationProvider.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// Approves the fine tuning.
        /// </summary>
        private void ApproveFineTuning()
        {
            LogManager.Log("Approve fine tuning command pressed.");

            Job.JobEditingState = BL.Enumerations.EditingStates.Default;
            Job.JobFineTuningStatus = BL.Enumerations.FineTuningStatuses.Approved;

            foreach (var item in ApprovalFineTuneItems)
            {
                foreach (var stop in item.BrushStops)
                {
                    stop.Color = item.SelectedSuggestion.Color;
                }
            }


            Job.FineTuningApproveDate = DateTime.UtcNow;
            SaveJob(false);

            if (_jobs_fine_tune_items.ContainsKey(Job.Guid))
            {
                _jobs_fine_tune_items.Remove(Job.Guid);
            }

            SyncFineTuneItemsToBrushStops();
        }

        /// <summary>
        /// Repeats the fine tuning.
        /// </summary>
        private void RepeatFineTuning()
        {
            LogManager.Log("Repeat fine tuning command pressed.");

            Job.JobEditingState = BL.Enumerations.EditingStates.Default;
            Job.JobFineTuningStatus = BL.Enumerations.FineTuningStatuses.Unspecified;
        }

        #endregion

        #region Out Of Gamut Check Thread

        /// <summary>
        /// Iterates over all brush stops and checks for out of gamut.
        /// </summary>
        [HandleProcessCorruptedStateExceptions]
        private void CheckGamutThreadMethod()
        {
            while (true)
            {
                Thread.Sleep(500);

                if (Job != null && Job.Rml.Cct != null && IsVisible && (Job.ColorSpace != null && (Job.ColorSpace.Code == BL.Enumerations.ColorSpaces.RGB.ToInt32() || Job.ColorSpace.Code == BL.Enumerations.ColorSpaces.LAB.ToInt32())))
                {
                    var brushStops = Job.Segments.SelectMany(x => x.BrushStops).Where(x => !x.Corrected && !x.OutOfGamutChecked).ToList();

                    foreach (var stop in brushStops)
                    {
                        try
                        {
                            stop.IsOutOfGamut = _converter.IsOutOfGamut(stop);
                            stop.OutOfGamutChecked = true;
                        }
                        catch (AccessViolationException)
                        {
                            LogManager.Log($"Out of gamut check failed for brush stop {stop.StopIndex} at segment {stop.Segment.SegmentIndex}.", LogCategory.Warning);
                            continue;
                        }
                        catch
                        {
                            LogManager.Log($"Out of gamut check failed for brush stop {stop.StopIndex} at segment {stop.Segment.SegmentIndex}.", LogCategory.Warning);
                        }
                    }

                    if (brushStops.Count > 0)
                    {
                        InvokeUI(() =>
                        {
                            DyeCommand.RaiseCanExecuteChanged();
                            StartSampleDyeCommand.RaiseCanExecuteChanged();
                            StartFineTuningCommand.RaiseCanExecuteChanged();
                        });
                    }
                }
            }
        }

        #endregion

        #region Export Embroidery

        private async void ExportEmbroidery()
        {
            try
            {
                if (!StorageProvider.IsConnected)
                {
                    await NotificationProvider.ShowError("No storage device connected.");
                    return;
                }

                var result = await NavigationManager.
                  NavigateForResult<StorageModule,
                  Storage.Views.MainView, ExplorerFileItem,
                  Storage.Models.StorageNavigationRequest>(
                  new Storage.Models.StorageNavigationRequest()
                  {
                      Intent = Storage.Models.StorageNavigationIntent.SaveFile,
                      DefaultFileName = Job.Name + Path.GetExtension(Job.EmbroideryFileName),
                      Filter = Path.GetExtension(Job.EmbroideryFileName),
                      Title = "Export Embroidery File",
                  });

                if (result != null)
                {
                    File.WriteAllBytes(Path.HasExtension(result.Path) ? result.Path : result.Path + Path.GetExtension(Job.EmbroideryFileName), Job.EmbroideryFileData);
                    await NotificationProvider.ShowSuccess("Embroidery file exported successfully.");
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error exporting embroidery file.");
                await NotificationProvider.ShowError("An error occurred while trying to save the selected embroidery file.");
            }
        }

        #endregion

        #region IPPC ViewModel Overrides

        /// <summary>
        /// Called when the application has been started.
        /// </summary>
        public override void OnApplicationStarted()
        {
            base.OnApplicationStarted();

            MachineProvider.MachineOperator.PrintingEnded += MachineOperator_PrintingEnded;
        }

        private void MachineOperator_PrintingEnded(object sender, Integration.Operation.PrintingEventArgs e)
        {
            if (IsVisible)
            {
                _start_printing_btn.Push();
            }
        }

        /// <summary>
        /// Called when the navigation system has navigated to this VM view.
        /// </summary>
        public override void OnNavigatedTo()
        {
            if (!MachineProvider.MachineOperator.IsPrinting)
            {
                _start_printing_btn.Push();
            }

            base.OnNavigatedTo();
            LoadJob();
        }

        /// <summary>
        /// Called when the navigation system has navigated from this VM view.
        /// </summary>
        public override void OnNavigatedFrom()
        {
            _start_printing_btn.Pop();

            base.OnNavigatedFrom();
            _job_to_load_intent = JobNavigationIntent.Default;
        }

        /// <summary>
        /// Called before the navigation system navigates back from this object.
        /// Return false to abort the navigation.
        /// </summary>
        /// <returns></returns>
        public async override Task<bool> OnNavigateBackRequest()
        {
            bool result = true;

            if (!_can_navigate_back)
            {
                bool jobChainged = false;

                if (Job != null)
                {
                    string job_string = Job.ToJobFileWhenLoaded().ToString();
                    jobChainged = job_string != _current_job_string;
                }

                if (jobChainged)
                {
                    if (await NotificationProvider.ShowQuestion("Are you sure you want to exit this job without saving changes?"))
                    {
                        Job = null;
                        SegmentsCollectionView = null;
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    Job = null;
                    SegmentsCollectionView = null;
                }
            }

            return result;
        }

        public override void OnApplicationReady()
        {
            base.OnApplicationReady();

            _start_printing_btn = new StartPrintingButton(DyeCommand, MachineProvider.MachineOperator);
        }
        #endregion

        #region INavigationObjectReceiver

        public void OnNavigatedToWithObject(JobNavigationObject e)
        {
            _job_to_load_intent = e.Intent;
            _job_to_load = e.Job;
        }

        #endregion
    }
}