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

namespace Tango.PPC.UI.ViewModels
{
    /// <summary>
    /// Represents the external bridge view ViewModel.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    [TangoCreateWhenRegistered]
    public class ExternalBridgeViewVM : PPCViewModel
    {
        private bool _disconnecting;

        #region Properties

        private ExternalBridgeClientConnectedEventArgs _connection;
        /// <summary>
        /// Gets or sets the last client connection event arguments.
        /// </summary>
        public ExternalBridgeClientConnectedEventArgs Connection
        {
            get { return _connection; }
            set { _connection = value; RaisePropertyChangedAuto(); }
        }

        private User _user;
        /// <summary>
        /// Gets or sets the user connected user.
        /// </summary>
        public User User
        {
            get { return _user; }
            set { _user = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the close session command.
        /// </summary>
        public RelayCommand CloseSessionCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalBridgeViewVM"/> class.
        /// </summary>
        public ExternalBridgeViewVM()
        {
            CloseSessionCommand = new RelayCommand(CloseSession, () => !_disconnecting);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Closes the current session.
        /// </summary>
        private void CloseSession()
        {
            LogManager.Log("Disconnecting current external bridge session.");
            _disconnecting = true;
            InvalidateRelayCommands();
            ExternalBridgeService.DisconnectSession();
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Called when the navigation system has navigated to this VM view.
        /// </summary>
        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();

            _disconnecting = false;
            InvalidateRelayCommands();
        }

        /// <summary>
        /// Called when the application has been started.
        /// </summary>
        public override void OnApplicationStarted()
        {
            ExternalBridgeService.ConnectionRequest += ExternalBridgeService_ConnectionRequest;
            ExternalBridgeService.ClientDisconnected += ExternalBridgeService_ClientDisconnected;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the <see cref="ExternalBridgeService.ClientDisconnected"/> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void ExternalBridgeService_ClientDisconnected(object sender, EventArgs e)
        {
            LogManager.Log("External bridge client disconnected. Navigating to home module...");

            InvokeUI(() =>
            {
                NavigationManager.NavigateTo(NavigationView.HomeModule);
            });
        }

        /// <summary>
        /// Handles the <see cref="ExternalBridgeService.ConnectionRequest"/> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="ExternalBridgeClientConnectedEventArgs"/> instance containing the event data.</param>
        private void ExternalBridgeService_ConnectionRequest(object sender, ExternalBridgeClientConnectedEventArgs e)
        {
            LogManager.Log($"External bridge connection request received.\n{e.ToJsonString()}");

            if (e.Request.Password == MachineProvider.Machine.ExternalBridgePassword)
            {
                e.Confirmed = true;

                Connection = e;

                User = Adapter.Users.SingleOrDefault(x => x.Guid == e.Request.UserGuid);

                if (User != null)
                {
                    LogManager.Log($"External bridge connection user has been identified as {User.Contact.FullName}");
                }

                LogManager.Log("Navigating to external bridge view...");
                InvokeUI(() =>
                {
                    NavigationManager.NavigateTo(NavigationView.ExternalBridgeView, false);
                });
            }
            else
            {
                LogManager.Log("Connection password did not match the machine external bridge password.");
            }
        }

        #endregion
    }
}
id='n889' href='#n889'>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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.BL;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core.Commands;
using Tango.Core.DI;
using Tango.DragAndDrop;
using Tango.PPC.Common;
using Tango.PPC.Common.Messages;
using Tango.PPC.Jobs.Dialogs;
using Tango.PPC.Jobs.Messages;
using Tango.PPC.Jobs.Views;
using System.Data.Entity;
using Tango.BL.Builders;
using Tango.PPC.Jobs.NavigationObjects;
using Tango.PPC.Storage;
using Tango.Explorer;
using System.IO;
using Google.Protobuf;
using Tango.PMR.Exports;
using Tango.Settings;
using Tango.Integration.ExternalBridge;
using System.Windows.Media;
using Tango.PMR.TCC;
using Tango.Pulse;
using System.Windows.Media.Imaging;
using Tango.Touch.Components;
using Tango.PPC.Jobs.ViewContracts;
using Tango.Core.ExtensionMethods;
using Tango.PPC.Common.Synchronization;
using Tango.PPC.Jobs.NotificationItems;
using Tango.PPC.Storage.Models;
using Tango.BL.Helpers;
using Tango.ColorConversion;
using Tango.PPC.Jobs.Models;

namespace Tango.PPC.Jobs.ViewModels
{
    /// <summary>
    /// Represents the jobs list view model.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    public class JobsViewVM : PPCViewModel<IJobsView>
    {
        private ObservablesContext _db; //Holds the db context for the job list.
        private ObservableCollection<ColorCatalog> _catalogs; //Holds the available color catalogs for the site.
        private ObservableCollection<Rml> _rmls; //Holds the available RML for the site.
        private ObservableCollection<SpoolType> _spoolTypes;
        private List<ColorSpace> _colorSpaces; //Holds the available color spaces.
        private bool _isJobsSynchronizationNotificationActive;

        public enum JobsCategory
        {
            Draft,
            History
        }

        #region Properties

        private ObservableCollection<Job> _jobs;
        /// <summary>
        /// Gets or sets the collection of jobs.
        /// </summary>
        public ObservableCollection<Job> Jobs
        {
            get { return _jobs; }
            set { _jobs = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _draftJobsCollectionView;
        /// <summary>
        /// Gets or sets the jobs collection view.
        /// </summary>
        public ICollectionView DraftJobsCollectionView
        {
            get { return _draftJobsCollectionView; }
            set
            {
                _draftJobsCollectionView = value;
                RaisePropertyChangedAuto();
            }
        }

        private ICollectionView _historyJobsCollectionView;
        /// <summary>
        /// Gets or sets the jobs collection view.
        /// </summary>
        public ICollectionView HistoryJobsCollectionView
        {
            get { return _historyJobsCollectionView; }
            set
            {
                _historyJobsCollectionView = value;
                RaisePropertyChangedAuto();
            }
        }

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

        private bool _isLoadingJobs;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is loading jobs.
        /// </summary>
        public bool IsLoadingJobs
        {
            get { return _isLoadingJobs; }
            set { _isLoadingJobs = value; RaisePropertyChangedAuto(); }
        }

        private bool _isMultiSelecting;
        /// <summary>
        /// Gets or sets a value indicating whether this the jobs list is in multi select mode.
        /// </summary>
        public bool IsMultiSelecting
        {
            get { return _isMultiSelecting; }
            set { _isMultiSelecting = value; RaisePropertyChangedAuto(); }
        }

        private int _selectedCategoryIndex;
        /// <summary>
        /// Gets or sets the index of the selected category.
        /// </summary>
        public int SelectedCategoryIndex
        {
            get { return _selectedCategoryIndex; }
            set
            {
                _selectedCategoryIndex = value;
                RaisePropertyChangedAuto();
                RaisePropertyChanged(nameof(SelectedCategory));
            }
        }

        /// <summary>
        /// Gets or sets the selected category.
        /// </summary>
        public JobsCategory SelectedCategory
        {
            get { return (JobsCategory)SelectedCategoryIndex; }
            set
            {
                if (SelectedCategoryIndex != value.ToInt32())
                {
                    SelectedCategoryIndex = value.ToInt32();
                    Filter = null;
                }
            }
        }

        private String _filter;
        /// <summary>
        /// Gets or sets the search filter.
        /// </summary>
        public String Filter
        {
            get { return _filter; }
            set { _filter = value; RaisePropertyChangedAuto(); OnFilterChanged(); }
        }

        private ICollectionFilter _collectionFilter;
        public ICollectionFilter CollectionFilter
        {
            get { return _collectionFilter; }
            set { _collectionFilter = value; RaisePropertyChangedAuto(); }
        }


        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the job selected command.
        /// </summary>
        public RelayCommand<Object> JobSelectedCommand { get; set; }

        /// <summary>
        /// Gets or sets the job drag and drop command.
        /// </summary>
        public RelayCommand<DropEventArgs> JobDragedDroppedCommand { get; set; }

        /// <summary>
        /// Gets or sets the clear selection command.
        /// </summary>
        public RelayCommand ClearSelectionCommand { get; set; }

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

        /// <summary>
        /// Gets or sets the delete jobs command.
        /// </summary>
        public RelayCommand DeleteJobsCommand { get; set; }

        /// <summary>
        /// Gets or sets the clone jobs command.
        /// </summary>
        public RelayCommand CloneJobsCommand { get; set; }

        /// <summary>
        /// Gets or sets the export job command.
        /// </summary>
        public RelayCommand ExportJobCommand { get; set; }
        
        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="JobsViewVM"/> class.
        /// </summary>
        public JobsViewVM()
        {
            Jobs = new ObservableCollection<Job>();
            SelectedJobs = new ObservableCollection<Job>();

            JobSelectedCommand = new RelayCommand<Object>((x) => SelectJob(x as Job));
            JobDragedDroppedCommand = new RelayCommand<DropEventArgs>((e) =>
            {
                Job draggedJob = e.Draggable.DataContext as Job;
                Job droppedJob = e.Droppable.DataContext as Job;

                DragAndDropJob(draggedJob, droppedJob);
            });

            ClearSelectionCommand = new RelayCommand(ClearSelection);
            AddJobCommand = new RelayCommand(() => AddNewJob());
            DeleteJobsCommand = new RelayCommand(() => DeleteJobs(SelectedJobs));
            CloneJobsCommand = new RelayCommand(() => CloneJobs(SelectedJobs));
            ExportJobCommand = new RelayCommand(ExportJob);
            
            RegisterForMessage<JobRemovedMessage>(HandleJobRemovedMessage);
            RegisterForMessage<JobSavedMessage>(HandleJobSavedMessage);
            RegisterForMessage<NavigatedToJobsModuleMessage>((x) => Filter = null);

            CollectionFilter = new DefaultCollectionFilter();
            CollectionFilter.RegisterFilter(item =>
            {
                var job = item as Job;

                if (job != null)
                {
                    if (String.IsNullOrEmpty(Filter))
                    {
                        return true;
                    }
                    else
                    {
                        return (job.Name.ToLower().Contains(Filter.ToLower()) || (job.Customer != null && job.Customer.Name.ToLower().StartsWith(Filter.ToLower())));
                    }
                }
                else
                {
                    return true;
                }
            });
        }

        #endregion

        #region Drag & Drop

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

            if (draggedJob.JobIndex > droppedJob.JobIndex)
            {
                draggedJob.JobIndex = droppedJob.JobIndex - 1;
            }
            else
            {
                draggedJob.JobIndex = droppedJob.JobIndex + 1;
            }

            int index = 1;

            foreach (var job in Jobs.OrderBy(x => x.JobIndex))
            {
                job.JobIndex = index++;
            }

            DraftJobsCollectionView.Refresh();
        }

        #endregion

        #region Job Selection & Loading

        /// <summary>
        /// Selects the job.
        /// </summary>
        /// <param name="job">The job.</param>
        public async void SelectJob(Job job, bool directlyToEdit = false)
        {
            //if (!ApplicationManager.IsInTechnicianMode && job.ColorSpace != null && job.ColorSpace.Code == ColorSpaces.Volume.ToInt32())
            //{
            //    await NotificationProvider.ShowError("The selected job is supported only in technician mode.");
            //    return;
            //}

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

            RaiseMessage(new JobSelectedMessage() { Job = job, Context = _db });

            if (!directlyToEdit && MachineProvider.MachineOperator.CanPrint)
            {
                await NavigationManager.NavigateWithObject<JobsV2Module, JobSummeryView, JobSummeryNavigationObject>(new JobSummeryNavigationObject()
                {
                    Context = _db,
                    Job = job,
                });
            }
            else
            {
                await NavigationManager.NavigateTo<JobsV2Module>(nameof(JobView));
            }
        }

        /// <summary>
        /// Loads the jobs from database.
        /// </summary>
        public void LoadJobs(Action onCompleted = null)
        {
            try
            {
                LogManager.Log("Loading machine jobs...");

                Task.Factory.StartNew(() =>
                {
                    IsLoadingJobs = true;

                    Thread.Sleep(500);

                    _db = ObservablesContext.CreateDefault();

                    _colorSpaces = _db.ColorSpaces.ToList();

                    var jobs = new JobsCollectionBuilder(_db).Set(x => x.MachineGuid == MachineProvider.Machine.Guid).WithSegments().WithBrushStops().WithCustomer().WithColorSpace().WithSegmentsGroups().Build();

                    InvokeUI(() =>
                    {
                        Jobs = jobs;
                        DraftJobsCollectionView = new ListCollectionView(Jobs);
                        DraftJobsCollectionView.SortDescriptions.Add(new SortDescription(nameof(Job.LastUpdated), ListSortDirection.Descending));
                        DraftJobsCollectionView.Filter = new Predicate<object>(x =>
                        {
                            var job = x as Job;
                            return job.JobStatus == JobStatuses.Draft;
                        });


                        HistoryJobsCollectionView = new ListCollectionView(Jobs);
                        HistoryJobsCollectionView.SortDescriptions.Add(new SortDescription(nameof(Job.LastUpdated), ListSortDirection.Descending));
                        HistoryJobsCollectionView.Filter = new Predicate<object>(x =>
                        {
                            var job = x as Job;
                            return job.JobStatus != JobStatuses.Draft;
                        });

                        IsLoadingJobs = false;
                        LogManager.Log("Machine jobs loaded!");
                        onCompleted?.Invoke();
                    });
                });
            }
            catch (Exception ex)
            {
                LogManager.Log(ex);
                NotificationProvider.ShowError("An error occurred while trying to load the machine jobs.");
            }
        }

        /// <summary>
        /// Clears the job selection.
        /// </summary>
        public void ClearSelection()
        {
            SelectedJobs.Clear();
            IsMultiSelecting = false;
        }

        /// <summary>
        /// Adds a new job.
        /// </summary>
        private async void AddNewJob(Color? colorProfile = null, TwnFile twnFile = null)
        {
            try
            {
                LogManager.Log("Adding new job...");

                var settings = SettingsManager.Default.GetOrCreate<JobsModuleSettings>();

                var machine = MachineProvider.Machine;
               
                if(_rmls.Count == 0)
                {
                    await Task.Delay(200);
                }
                var selectedRmlGuid = Settings.DefaultRmlGuid;
                JobCreationViewVM vm = new JobCreationViewVM( _spoolTypes.ToList(), _rmls.ToList(), selectedRmlGuid, 0, false );
                
                var selectedSpoolTypeGuid = Settings.SpoolTypeGuid;
                vm.SelectedSpoolType = false == String.IsNullOrEmpty(selectedSpoolTypeGuid ) ? _spoolTypes.FirstOrDefault( x=>x.Guid == selectedSpoolTypeGuid) : _spoolTypes.FirstOrDefault(x=>x.Type == SpoolTypes.StandardSpool);
                if (twnFile == null)
                {
                    vm = await NotificationProvider.ShowDialog<JobCreationViewVM>(vm);
                    if (!vm.DialogResult) return;
                    
                    if(vm.SelectedRML != null)
                    {
                        selectedRmlGuid = vm.SelectedRML.Guid;
                    }
                    if(vm.SelectedSpoolType != null)
                    {
                        selectedSpoolTypeGuid = vm.SelectedSpoolType.Guid;
                    }
                    
                }
                
                Job job = new Job();
                job.LastUpdated = DateTime.UtcNow;
                job.JobSource = JobSource.Local;
                job.Name = vm.JobName;
                job.NumberOfHeads = 1;
                job.NumberOfUnits = 1;
                job.SampleUnitsOrMeters = 1;
                job.CreationDate = DateTime.UtcNow;
                job.JobStatus = JobStatuses.Draft;
                job.EnableInterSegment = vm.WhiteGap > 0;
                job.InterSegmentLength = vm.WhiteGap;
                //job.JobType = vm.SelectedJobType;
                job.EnableLubrication = true;
                //job.ColorSpaceGuid = Adapter.ColorSpaces.FirstOrDefault(x => x.Code == vm.SelectedColorSpace.ToInt32()).Guid;
                //job.ColorSpace = _colorSpaces.SingleOrDefault(x => x.Guid == job.ColorSpaceGuid);
                job.MachineGuid = MachineProvider.Machine.Guid;
                job.UserGuid = null;
                job.RmlGuid = selectedRmlGuid;
                job.WindingMethodGuid = Adapter.WindingMethods.FirstOrDefault().Guid;
                job.SpoolTypeGuid = selectedSpoolTypeGuid;
                
                if (Jobs.Count > 0)
                {
                    job.JobIndex = Jobs.Max(x => x.JobIndex) + 1;
                }

                if (colorProfile == null)
                {
                    var segment = job.AddSolidSegment(Settings.DefaultSegmentLength > 0 ? Settings.DefaultSegmentLength : 100);
                    segment.BrushStops.Clear();
                }
                else
                {
                    var segment = job.AddSolidSegment(colorProfile.Value, Settings.DefaultSegmentLength > 0 ? Settings.DefaultSegmentLength : 100);
                    segment.BrushStops.Clear();
                    job.Name = $"SnapMatch {colorProfile.Value.R}, {colorProfile.Value.G}, {colorProfile.Value.B}";
                }

                if (twnFile != null)
                {
                    job.Name = twnFile.Name;
                    job.NumberOfUnits = Math.Max(twnFile.NumberOfCopies, 1);
                    job.EmbroideryFileName = twnFile.Name + "." + twnFile.EmbroideryFileFormat;
                    job.EmbroideryFileData = twnFile.EmbroideryFile;
                    job.EmbroideryJpeg = twnFile.ThumbnailData;

                    job.Segments.Clear();

                    int index = 1;

                    foreach (var segment in twnFile.Segments)
                    {
                        Segment s = new Segment();
                        s.Job = job;
                        s.SegmentIndex = index++;
                        s.Name = "Embroidery Segment";
                        s.Length = segment.Length / 100d;

                        int sIndex = 1;

                        foreach (var stop in segment.BrushStops)
                        {
                            BrushStop st = new BrushStop();
                            st.Segment = s;
                            st.StopIndex = sIndex++;
                            st.OffsetPercent = stop.Offset * 100d;
                            st.Red = stop.R;
                            st.Green = stop.G;
                            st.Blue = stop.B;
                            st.ColorSpaceGuid = job.ColorSpaceGuid;
                            s.BrushStops.Add(st);
                        }

                        job.Segments.Add(s);
                    }
                }

                _db.Jobs.Add(job);

                await _db.SaveChangesAsync();

                Jobs.Add(job);

                LogManager.Log($"Job {job.Name} added successfully.");

                RaiseMessage(new JobSelectedMessage() { Job = job, Context = _db });
                

                await Task.Delay(200);
                await NavigationManager.NavigateWithObject<JobsV2Module, JobView, JobNavigationObject>(new JobNavigationObject()
                {
                    Job = job,
                    Intent = JobNavigationIntent.NewJob
                });
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error creating new job.");
                await NotificationProvider.ShowError("An error occurred while trying to add a new job.");
            }
        }
        
        /// <summary>
        /// Deletes the specified jobs from db.
        /// </summary>
        /// <param name="jobs">The jobs.</param>
        private async void DeleteJobs(ObservableCollection<Job> jobs)
        {
            try
            {
                LogManager.Log($"Removing selected jobs:\n{jobs.Select(x => x.Name).ToList().ToJsonString()}");

                if (await NotificationProvider.ShowQuestion("Are you sure you want to delete the selected jobs"))
                {
                    foreach (var job in jobs)
                    {
                        await job.DeleteCascadeAsync(_db);
                        Jobs.Remove(job);
                    }

                    await _db.SaveChangesAsync();
                    ClearSelection();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error removing selected jobs.");
                await NotificationProvider.ShowError("An error occurred while trying to remove the selected jobs.");
            }
        }

        /// <summary>
        /// Clones the specified jobs.
        /// </summary>
        /// <param name="jobs">The jobs.</param>
        private async void CloneJobs(ObservableCollection<Job> jobs)
        {
            try
            {
                LogManager.Log($"Cloning selected jobs:\n{jobs.Select(x => x.Name).ToList().ToJsonString()}");

                int index = Jobs.Max(x => x.JobIndex);

                List<Job> clonedJobs = new List<Job>();

                foreach (var job in SelectedJobs)
                {
                    var cloned = job.Clone();
                    cloned.JobIndex = ++index;
                    _db.Jobs.Add(cloned);
                    clonedJobs.Add(cloned);
                }

                await _db.SaveChangesAsync();

                foreach (var job in clonedJobs)
                {
                    Jobs.Add(job);
                }

                ClearSelection();
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error cloning selected jobs.");
                await NotificationProvider.ShowError("An error occurred while trying to clone the selected jobs.");
            }
        }

        /// <summary>
        /// Called when the search filter has been changed
        /// </summary>
        private void OnFilterChanged()
        {
            if (DraftJobsCollectionView != null && HistoryJobsCollectionView != null)
            {
                CollectionFilter.RaiseFilterChanged();
                View.ScrollToTop();
            }
        }

        #endregion

        #region Message Handling

        /// <summary>
        /// Handles the job removed message.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void HandleJobRemovedMessage(JobRemovedMessage msg)
        {
            try
            {
                LogManager.Log("JobRemovedMessage message received, removing job from list...");
                var job = Jobs.SingleOrDefault(x => x.Guid == msg.Job.Guid);
                Jobs.Remove(job);
                _db.Entry(job).State = System.Data.Entity.EntityState.Detached;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Could not remove job");
            }
        }

        /// <summary>
        /// Handles the job saved message.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void HandleJobSavedMessage(JobSavedMessage msg)
        {
            LogManager.Log("JobSavedMessage message received.");
            LoadJobs();
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Called when the application has been started.
        /// </summary>
        public override void OnApplicationStarted()
        {
            BrushStop.ColorSynchronizationMode = BrushStop.ColorSynchronizationModes.None;

            LoadJobs();
            ExternalBridgeService.ColorProfileRequest += ExternalBridgeService_ColorProfileRequest;
        }

        public async override void OnApplicationReady()
        {
            base.OnApplicationReady();
            StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Job.Extension, HandleJobFileLoaded);
            StorageProvider.RegisterFileHandler(ExplorerFileDefinition.ColorProfile.Extension, HandleColorProfileFileLoaded);
            StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Pulse.Extension, HandlePulseFileLoaded);
            StorageProvider.RegisterFileHandler(ExplorerFileDefinition.CsvFile.Extension, HandleCsvJobFileLoaded);

            //Load catalogs.
            using (ObservablesContext db = ObservablesContext.CreateDefault())
            {
                _catalogs = await new CatalogsCollectionBuilder(db).SetAll().ForSite(MachineProvider.Machine.SiteGuid).BuildAsync();
                _rmls = await new RmlsCollectionBuilder(db).SetAll().WithSpools().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).BuildAsync();
                //_rmls = (await new RmlsCollectionBuilder(db).SetAll().WithSpools().BuildAsync()).OrderBy(x => x.FinalName).ToObservableCollection();
                _spoolTypes = db.SpoolTypes.ToObservableCollection();
            }

            MachineDataSynchronizer.SynchronizationEnded += MachineDataSynchronizer_SynchronizationEnded;
        }

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();
            JobViewVM._start_printing_btn?.Pop();
            Filter = null;
        }

        #endregion

        #region Job Export

        private async void ExportJob()
        {
            var selected_job = SelectedJobs.FirstOrDefault();
            if (selected_job == null) return;

            var selectedJobs = SelectedJobs.ToList();

            ClearSelection();

            var result = await NavigationManager.
                NavigateForResult<StorageModule,
                Storage.Views.MainView, ExplorerFileItem,
                StorageNavigationRequest>(
                new StorageNavigationRequest()
                {
                    Intent = selectedJobs.Count == 1 ? StorageNavigationIntent.SaveFile : StorageNavigationIntent.SaveFiles,
                    DefaultFileName = selected_job.Name,
                    Filter = ExplorerFileDefinition.Job.Extension,
                    Title = selectedJobs.Count == 1 ? "Save Job File" : "Save Job Files",
                });

            if (result != null)
            {
                if (selectedJobs.Count == 1)
                {
                    try
                    {
                        var jobFile = await selected_job.ToJobFile();

                        using (FileStream fs = new FileStream(result.Path + ExplorerFileDefinition.Job.Extension, FileMode.Create))
                        {
                            jobFile.WriteTo(fs);
                        }

                        await NotificationProvider.ShowSuccess("Job saved successfully.");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"Error saving job {selected_job.Name} to file.");
                        await NotificationProvider.ShowError($"An error occurred while trying to save the job.\n{ex.Message}");
                    }
                }
                else
                {
                    foreach (var job in selectedJobs)
                    {
                        try
                        {
                            var jobFile = await job.ToJobFile();

                            using (FileStream fs = new FileStream(Path.Combine(result.Path, jobFile.Name.ToValidFileName()) + ExplorerFileDefinition.Job.Extension, FileMode.Create))
                            {
                                jobFile.WriteTo(fs);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, $"Error saving job {job.Name} to file.");
                            await NotificationProvider.ShowError($"An error occurred while trying to save the job.\n{ex.Message}");
                        }
                    }

                    await NotificationProvider.ShowSuccess("Jobs saved successfully.");
                }
            }
        }

        #endregion

        #region Handle Job File Loading From Storage

        private async void HandleJobFileLoaded(List<ExplorerFileItem> jobFiles)
        {
            var vm = await NotificationProvider.ShowDialog<ImportJobViewVM>();

            if (vm.DialogResult)
            {
                using (ObservablesContext jobContext = ObservablesContext.CreateDefault())
                {
                    foreach (var jobFile in jobFiles)
                    {
                        try
                        {
                            JobFile jFile = JobFile.Parser.ParseFrom(File.ReadAllBytes(jobFile.Path));
                            var job = await Job.FromJobFile(jFile, MachineProvider.Machine.Guid, null);
                            job.JobSource = JobSource.Local;
                            jobContext.Jobs.Add(job);
                            await jobContext.SaveChangesAsync();
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, $"Error occurred while trying to import job from file {jobFile.Path}.");
                            await NotificationProvider.ShowError($"An error occurred while trying to import the selected job file.\n{ex.Message}");
                        }
                    }

                    LoadJobs(() =>
                    {
                        //Editing of a job is currently deprecated due to enabling multiple job imports.
                        //if (vm.ImportAndEdit)
                        //{
                        //    var postJob = Jobs.SingleOrDefault(x => x.Guid == job.Guid);
                        //    if (postJob != null)
                        //    {
                        //        SelectJob(postJob, true);
                        //    }
                        //}
                    });
                }
            }
        }

        #endregion

        #region Handle CSV Job File Loading From Storage

        private async void HandleCsvJobFileLoaded(List<ExplorerFileItem> files)
        {
            var item = files.FirstOrDefault();
            if (item == null) return;

            var vm = new ImportCsvJobViewVM();
            vm.Name = Path.GetFileNameWithoutExtension(item.Name);
            await vm.Init();
            await NotificationProvider.ShowDialog<ImportCsvJobViewVM>(vm);

            if (vm.DialogResult && vm.SelectedRml != null)
            {
                try
                {
                    NotificationProvider.SetGlobalBusyMessage("Importing job from file...");

                    using (ObservablesContext db = ObservablesContext.CreateDefault())
                    {
                        var segments = await SegmentsCsvHelper.FromFile(item.Path, MachineProvider.Machine, db);

                        Job job = new Job();
                        job.LastUpdated = DateTime.UtcNow;
                        job.JobSource = JobSource.Local;
                        job.Name = vm.Name;
                        job.NumberOfHeads = 1;
                        job.NumberOfUnits = 1;
                        job.SampleUnitsOrMeters = 1;
                        job.CreationDate = DateTime.UtcNow;
                        job.JobStatus = JobStatuses.Draft;
                        job.JobType = JobTypes.Knitting;
                        job.EnableLubrication = true;
                        job.MachineGuid = MachineProvider.Machine.Guid;
                        job.RmlGuid = vm.SelectedRml.Guid;
                        job.Machine = await new MachineBuilder(db).Set(job.MachineGuid).WithCats().WithConfiguration().BuildAsync();
                        job.Rml = await new RmlBuilder(db).Set(job.RmlGuid).WithActiveParametersGroup().WithCAT(MachineProvider.Machine.Guid).WithCCT().WithGbdAndLub().WithLiquidFactors().BuildAsync();
                        job.WindingMethodGuid = Adapter.WindingMethods.FirstOrDefault().Guid;
                        job.SpoolTypeGuid = Settings.SpoolTypeGuid != null ? Settings.SpoolTypeGuid : Adapter.SpoolTypes.FirstOrDefault().Guid;

                        foreach (var segment in segments)
                        {
                            segment.Job = job;
                            job.Segments.Add(segment);
                        }

                        IColorConverter converter = new DefaultColorConverter();

                        foreach (var stop in segments.SelectMany(x => x.BrushStops.Where(y => y.BrushColorSpace == ColorSpaces.Volume)))
                        {
                            var output = converter.Convert(stop, false);
                            var suggestion = output.CreateSingleSuggestion();
                            stop.Color = suggestion.Color;
                        }

                        db.Jobs.Add(job);
                        await db.SaveChangesAsync();
                        LoadJobs();
                    }

                    NotificationProvider.ReleaseGlobalBusyMessage();
                }
                catch (Exception ex)
                {
                    NotificationProvider.ReleaseGlobalBusyMessage();
                    LogManager.Log(ex, "Error importing job from CSV.");
                    await NotificationProvider.ShowError($"Error importing job from csv file.\n{ex.FlattenMessage()}");
                }
            }
        }

        #endregion

        #region Handle TCC File Loading From Storage

        private async void HandleColorProfileFileLoaded(List<ExplorerFileItem> tccFiles)
        {
            var tccFile = tccFiles.FirstOrDefault();

            try
            {
                DetectionColorFile tcc = DetectionColorFile.Parser.ParseFrom(File.ReadAllBytes(tccFile.Path));

                var vm = await NotificationProvider.ShowDialog<ImportColorProfileViewVM>(new ImportColorProfileViewVM()
                {
                    Color = Color.FromRgb(
                       (byte)tcc.ProcessedColor.R,
                       (byte)tcc.ProcessedColor.G,
                       (byte)tcc.ProcessedColor.B),
                });

                if (vm.DialogResult)
                {
                    AddNewJob(vm.Color);
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error occurred while trying to import detection color from file {tccFile.Path}.");
                await NotificationProvider.ShowError($"An error occurred while trying to import the selected detection color.\n{ex.Message}");
            }
        }

        #endregion

        #region Handle Pulse TWN Loading From Storage

        private async void HandlePulseFileLoaded(List<ExplorerFileItem> twnFiles)
        {
            var twnFile = twnFiles.FirstOrDefault();

            TwnFile twn = TwnFile.FromFile(twnFile.Path);
            BitmapSource preview = twn.Thumbnail.ToBitmapSource();

            var vm = await NotificationProvider.ShowDialog<ImportTwnFileViewVM>(new ImportTwnFileViewVM()
            {
                Thumbnail = preview,
            });

            if (vm.DialogResult)
            {
                AddNewJob(null, twn);
            }
        }

        #endregion

        #region Handle New Synchronized Jobs

        private void MachineDataSynchronizer_SynchronizationEnded(object sender, SynchronizationEndedEventArgs e)
        {
            if (e.NewChangedJobs > 0 && !_isJobsSynchronizationNotificationActive)
            {
                _isJobsSynchronizationNotificationActive = true;

                var item = NotificationProvider.PushNotification<NewSynchronizardJobsNotificationItem>();
                item.Pressed += (_, __) =>
                {
                    _isJobsSynchronizationNotificationActive = false;
                    LoadJobs(() =>
                    {
                        NotificationProvider.ShowSuccess("Your job list is now synchronized.");
                    });
                };
                item.Closed += (_, __) =>
                {
                    _isJobsSynchronizationNotificationActive = false;
                };
            }
        }

        #endregion

        #region Color Profile Request

        private void ExternalBridgeService_ColorProfileRequest(object sender, ColorProfileRequestEventArgs e)
        {
            InvokeUI(async () =>
            {
                var vm = await NotificationProvider.ShowDialog<ColorProfileReceivedViewVM>(new ColorProfileReceivedViewVM()
                {
                    Color = Color.FromRgb(
                        (byte)e.Request.DetectionColor.R,
                        (byte)e.Request.DetectionColor.G,
                        (byte)e.Request.DetectionColor.B),
                });

                if (vm.DialogResult)
                {
                    e.Approve();
                    AddNewJob(vm.Color);
                }
                else
                {
                    e.Decline();
                }
            });
        }

        #endregion
    }
}