using Microsoft.Win32; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using Tango.BL; using Tango.BL.Builders; using Tango.BL.Calibration; using Tango.BL.Entities; using Tango.Core.Commands; using Tango.MachineStudio.Common; using Tango.MachineStudio.Common.Notifications; using System.Data.Entity; using Tango.Core.ExtensionMethods; using Tango.MachineStudio.Common.Authentication; using Tango.BL.ActionLogs; using Tango.BL.DTO; using Tango.BL.Enumerations; using Tango.MachineStudio.ThreadExtensions.Contracts; using Tango.MachineStudio.ThreadExtensions.Views; using Tango.MachineStudio.ThreadExtensions.Models; using Tango.Settings; namespace Tango.MachineStudio.ThreadExtensions.ViewModels { public class MainViewVM : StudioViewModel { private INotificationProvider _notification; private IAuthenticationProvider _authentication; private IActionLogManager _actionLogManager; private ObservablesContext _rmlExtentions_context; private ObservablesContext _active_context; private List _allUsers; #region properties //private ObservableCollection _rmlsExtension; //public ObservableCollection RmlsExtensions //{ // get { return _rmlsExtension; } // set { _rmlsExtension = value; // RaisePropertyChangedAuto(); } //} private List _rmlExtensions; public List RmlExtensions { get { return _rmlExtensions; } set { _rmlExtensions = value; RaisePropertyChangedAuto(); } } private RmlsExtension _ActiveRMLExtension; public RmlsExtension ActiveRMLExtension { get { return _ActiveRMLExtension; } set { _ActiveRMLExtension = value; RaisePropertyChangedAuto(); } } private Rml _activeRML; public Rml ActiveRML { get { return _activeRML; } set { _activeRML = value; RaisePropertyChangedAuto(); } } private RmlExtensionModel _selectedRMLExtension; public RmlExtensionModel SelectedRMLExtension { get { return _selectedRMLExtension; } set { _selectedRMLExtension = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } private ICollectionView _rmlExtCollectionView; /// /// Gets or sets the RML collection view. /// public ICollectionView RmlExtCollectionView { get { return _rmlExtCollectionView; } set { _rmlExtCollectionView = value; RaisePropertyChangedAuto(); } } private ObservableCollection _applications; public ObservableCollection Applications { get { return _applications; } set { _applications = value; RaisePropertyChangedAuto(); } } private ObservableCollection _brands; public ObservableCollection Brands { get { return _brands; } set { _brands = value; RaisePropertyChangedAuto(); } } private ObservableCollection _yarnWhiteShade; public ObservableCollection YarnWhiteShade { get { return _yarnWhiteShade; } set { _yarnWhiteShade = value; RaisePropertyChangedAuto(); } } private ObservableCollection _enduse; public ObservableCollection EndUse { get { return _enduse; } set { _enduse = value; RaisePropertyChangedAuto(); } } private ObservableCollection _units; public ObservableCollection Units { get { return _units; } set { _units = value; RaisePropertyChangedAuto(); } } private ObservableCollection _family; public ObservableCollection Family { get { return _family; } set { _family = value; RaisePropertyChangedAuto(); } } private ObservableCollection _geometry; public ObservableCollection Geometry { get { return _geometry; } set { _geometry = value; RaisePropertyChangedAuto(); } } private ObservableCollection _glosslevel; public ObservableCollection GlossLevel { get { return _glosslevel; } set { _glosslevel = value; RaisePropertyChangedAuto(); } } private ObservableCollection _group; public ObservableCollection Group { get { return _group; } set { _group = value; RaisePropertyChangedAuto(); } } //private ObservableCollection _manufacturer; //public ObservableCollection Manufacturer //{ // get { return _manufacturer; } // set { _manufacturer = value; RaisePropertyChangedAuto(); } //} private List _manufacturers; public List Manufacturers { get { return _manufacturers; } set { _manufacturers = value; RaisePropertyChangedAuto(); } } private ObservableCollection _materials; public ObservableCollection Materials { get { return _materials; } set { _materials = value; RaisePropertyChangedAuto(); } } private ObservableCollection _subFamilies; public ObservableCollection SubFamilies { get { return _subFamilies; } set { _subFamilies = value; RaisePropertyChangedAuto(); } } private ObservableCollection _texturing; public ObservableCollection Texturing { get { return _texturing; } set { _texturing = value; RaisePropertyChangedAuto(); } } private ObservableCollection _yarnTypes; public ObservableCollection YarnTypes { get { return _yarnTypes; } set { _yarnTypes = value; RaisePropertyChangedAuto(); } } private ObservableCollection _industrySector; public ObservableCollection IndustrySector { get { return _industrySector; } set { _industrySector = value; RaisePropertyChangedAuto(); } } private String _Filter; /// /// Gets or sets the search filter. /// public String Filter { get { return _Filter; } set { _Filter = value; RaisePropertyChangedAuto(); OnFilterChanged(); } } private async void OnFilterChanged() { await LoadRmlExtentions(); } private ColorParametersVewVM _colorParametersVewVM; public ColorParametersVewVM ColorParametersVewVM { get { return _colorParametersVewVM; } set { _colorParametersVewVM = value; RaisePropertyChangedAuto(); } } private TestResultsViewVM _testResultsViewVM; public TestResultsViewVM TestResultsViewVM { get { return _testResultsViewVM; } set { _testResultsViewVM = value; RaisePropertyChangedAuto(); } } protected Machine _selectedMachine; /// /// Gets or sets the selected machine. /// public Machine SelectedMachine { get { return _selectedMachine; } set { if (value != null && _selectedMachine != value) { _selectedMachine = value; SelectedMachineChanged(); RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } } private ObservableCollection _machines; /// /// Gets or sets the Machines. /// public ObservableCollection Machines { get { return _machines; } set { _machines = value; RaisePropertyChanged(nameof(Machines)); } } #endregion #region commands public RelayCommand SaveCommand { get; set; } public RelayCommand ManageRmlExtensionCommand { get; set; } public RelayCommand BackToThreadExtensionViewsCommand { get; set; } private async void BackToThreadExtensionViews(object obj) { View.NavigateTo(RMLExtensionNavigationView.RMLExtensionsView); await LoadRmlExtentions(); } #endregion public MainViewVM(INotificationProvider notificationProvider, IAuthenticationProvider authentication, IActionLogManager actionLogManager) { _notification = notificationProvider; _authentication = authentication; _actionLogManager = actionLogManager; BackToThreadExtensionViewsCommand = new RelayCommand(BackToThreadExtensionViews, () => IsFree); SaveCommand = new RelayCommand(Save, () => IsFree); ManageRmlExtensionCommand = new RelayCommand(() => LoadActiveRMLExtension(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); } public override void OnApplicationReady() { } #region Loading private async Task LoadRmlExtentions() { var filter = Filter.ToStringOrEmpty().ToLower(); try { IsFree = false; using (_notification.PushTaskItem("Loading RmlExtentions...")) { if (_rmlExtentions_context != null) _rmlExtentions_context.Dispose(); _rmlExtentions_context = ObservablesContext.CreateDefault(); Brands = _rmlExtentions_context.YarnBrands.ToObservableCollection(); _allUsers = await _rmlExtentions_context.Users.Include(x => x.Contact).ToListAsync(); var q = (from c in _rmlExtentions_context.Rmls.Where(x => x.Name.ToLower().Contains(filter)) join p in _rmlExtentions_context.RmlsExtensions on c.Guid equals p.RmlsGuid into ps from p in ps.DefaultIfEmpty() select new { RML = c, RMLExtesion = p }).Distinct().ToList().DistinctBy(x => x.RML.Guid) .Select(x => new RmlExtensionModel() { RMLGuid = x.RML.Guid, Guid = x.RMLExtesion == null? null : x.RMLExtesion.Guid, Name = x.RML.Name, Manufacturer = x.RML.Manufacturer, Brand = x.RMLExtesion == null ? "" : (Brands.Where( y => y.Guid == x.RMLExtesion.YarnBrandGuid).Select( z => z.Name).FirstOrDefault()), LinearDensity = (int) x.RML.FiberSize, CreatedBy = x.RMLExtesion == null ? "" : _allUsers.SingleOrDefault(y => y.Guid == x.RMLExtesion.UsersGuid).Contact.FullName, Created = x.RMLExtesion == null ? DateTime.Now : x.RMLExtesion.Created, LastUpdated = x.RMLExtesion == null ? DateTime.Now : x.RMLExtesion.LastUpdated, Status = x.RMLExtesion == null ? RMLExtensionStatus.New : x.RMLExtesion.RMLStatus }).ToList(); RmlExtensions = q; RmlExtCollectionView = CollectionViewSource.GetDefaultView(RmlExtensions); RmlExtCollectionView.SortDescriptions.Add(new SortDescription(nameof(Rml.LastUpdated), ListSortDirection.Ascending)); //RmlExtCollectionView.Filter = (rml) => //{ // RmlExtensionModel r = rml as RmlExtensionModel; // return String.IsNullOrWhiteSpace(Filter) // || r.Name.ToLower().Contains(Filter.ToLower()); //}; } } catch (Exception ex) { LogManager.Log(ex, $"Error loading RMLExtensions.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } private void LoadRmlProperties() { Applications = _active_context.YarnApplications.ToObservableCollection(); Brands = _active_context.YarnBrands.ToObservableCollection(); YarnWhiteShade = _active_context.YarnWhiteShades.ToObservableCollection(); EndUse = _active_context.MediaPurposes.ToObservableCollection(); Family = _active_context.YarnFamilies.ToObservableCollection(); Geometry = _active_context.FiberShapes.ToObservableCollection(); GlossLevel = _active_context.YarnGlossLevels.ToObservableCollection(); Group = _active_context.YarnGroups.ToObservableCollection(); //Manufacturer = _active_context.YarnManufacturers.ToObservableCollection(); Manufacturers = _active_context.YarnManufacturers.Select(x => x.Name).ToList(); Units = _active_context.LinearMassDensityUnits.ToObservableCollection(); Materials = _active_context.MediaMaterials.ToObservableCollection(); SubFamilies = _active_context.YarnSubFamilies.ToObservableCollection(); Texturing = _active_context.YarnTexturings.ToObservableCollection(); YarnTypes = _active_context.YarnTypes.ToObservableCollection(); IndustrySector = _active_context.YarnIndustrysectors.ToObservableCollection(); Machines = ObservablesStaticCollections.Instance.Machines.Select(x => new MachineModel() { Guid = x.Guid, Name = x.Name, SerialNumber = x.SerialNumber }).ToObservableCollection(); } private RmlsExtension GetNewRMLsExtension( string RML_Guid) { RmlsExtension rml_extention = new RmlsExtension(); rml_extention.Created = DateTime.UtcNow; rml_extention.RmlsGuid = RML_Guid; rml_extention.UsersGuid = _authentication.CurrentUser.Guid; //rml_extention.YarnManufacturer = Manufacturer.FirstOrDefault(); rml_extention.YarnBrand = Brands.FirstOrDefault(); rml_extention.Country = null; //rml_extention.YarnEndUse = EndUse.FirstOrDefault(); rml_extention.YarnApplication = Applications.FirstOrDefault(); rml_extention.YarnIndustrysector = IndustrySector.FirstOrDefault(); //rml_extention.YarnMaterial = Materials.FirstOrDefault(); rml_extention.YarnType = YarnTypes.FirstOrDefault(); rml_extention.YarnSubFamily = SubFamilies.FirstOrDefault(); rml_extention.YarnFamily = Family.FirstOrDefault(); rml_extention.YarnGroup = Group.FirstOrDefault(); rml_extention.YarnTexturing = Texturing.FirstOrDefault(); rml_extention.YarnWhiteShade = YarnWhiteShade.FirstOrDefault(); rml_extention.YarnGlossLevel = GlossLevel.FirstOrDefault(); rml_extention.TwistTpm = 0; rml_extention.YarnTwistDirections = TwistDirections.Unknown; rml_extention.MinElongation = 0.0; rml_extention.MaxElongation = 100.0; rml_extention.MinMaxForceN = 0.0; rml_extention.MaxMaxForceN = 100.0; rml_extention.MinElasticity = 0.0; rml_extention.MaxElasticity = 100.0; rml_extention.MinTenacity = 0.0; rml_extention.MaxTenacity = 100.0; rml_extention.Finishing = "Lubrication"; rml_extention.RMLStatus = RMLExtensionStatus.New; return rml_extention; } private async void LoadActiveRMLExtension(String guid) { using (_notification.PushTaskItem("Loading RML Extension...")) { try { IsFree = false; if (_active_context != null) { _active_context.Dispose(); } _active_context = ObservablesContext.CreateDefault(); LoadRmlProperties(); if (guid == null) { RmlsExtension rml_extention = GetNewRMLsExtension(SelectedRMLExtension.RMLGuid); _active_context.RmlsExtensions.Add(rml_extention); await _active_context.SaveChangesAsync(); guid = rml_extention.Guid; } ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) .Set(guid) .WithUser() .BuildAsync(); ActiveRML = new RmlBuilder(_active_context) .Set(SelectedRMLExtension.RMLGuid) .Build(); var machinesWithTest = _active_context.RmlExtensionTestResults.Select(x => x.MachineGuid).ToList(); var machinesWithTest2 = Join(_active_context.ColorProcessParameters.Select(y => y.MachineGuid), st1 => st1, st2=> st2, (st1, st2)=>).ToList(); Machines = ObservablesStaticCollections.Instance.Machines.Select(x => new MachineModel() { Guid = x.Guid, Name = x.Name, SerialNumber = x.SerialNumber }).ToObservableCollection(); var settings = SettingsManager.Default.GetOrCreate(); SelectedMachine = ObservablesStaticCollections.Instance.Machines.SingleOrDefault(x => x.SerialNumber == settings.LastVirtualMachineSerialNumber); ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); ColorParametersVewVM.RMLExtemtionGUID = guid; ColorParametersVewVM.SelectedMachineGUID = SelectedMachine.Guid; TestResultsViewVM = new TestResultsViewVM(_notification, _actionLogManager); TestResultsViewVM.RMLExtemtionGUID = guid; TestResultsViewVM.ThreadName = ActiveRML.Manufacturer; var machineGuidsWithTests = await _active_context.RmlExtensionTestResults.Where(x => x.RmlsExtensionsGuid == guid).Select(y => y.MachineGuid).ToListAsync(); if(machineGuidsWithTests.Count > 0) { } if (ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) { ColorParametersVewVM.SaveColorParameters -= UpdateStatus; ColorParametersVewVM.SaveColorParameters += UpdateStatus; TestResultsViewVM.SaveTestResults -= UpdateStatus; TestResultsViewVM.SaveTestResults += UpdateStatus; } View.NavigateTo(RMLExtensionNavigationView.RMLExtentionView); InvalidateRelayCommands(); IsFree = true; } catch (Exception ex) { //LogManager.Log($"Error loading RML '{ActiveRML.Name}'..."); _notification.ShowError($"Error loading the selected thread.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } } private async void RefreshView(String guid, String rmlGuid) { try { IsFree = false; LoadRmlProperties(); ActiveRML = ActiveRML = await new RmlBuilder(_active_context) .Set(rmlGuid) .BuildAsync(); ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) .Set(guid) .WithUser() .BuildAsync(); InvalidateRelayCommands(); IsFree = true; } catch (Exception ex) { //LogManager.Log($"Error loading RML '{ActiveRML.Name}'..."); _notification.ShowError($"Error refresh after save the selected thread.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } #endregion #region event handlers private async void UpdateStatus(object sender, EventArgs e) { IsFree = false; try { ColorParametersVewVM.SaveColorParameters -= UpdateStatus; TestResultsViewVM.SaveTestResults -= UpdateStatus; ActiveRMLExtension.RMLStatus = RMLExtensionStatus.InProgress; ActiveRMLExtension.LastUpdated = DateTime.UtcNow; await _active_context.SaveChangesAsync(); } catch (Exception ex) { LogManager.Log(ex, $"Error saving Status of RML Extension"); _notification.ShowError($"An error occurred while trying to save status of the current RML Extension.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } private void SelectedMachineChanged() { if(ColorParametersVewVM != null) { ColorParametersVewVM.SelectedMachineGUID = SelectedMachine.Guid; } } #endregion #region Save /// /// Saves this instance. /// private async void Save() { IsFree = false; try { using (_notification.PushTaskItem("Saving RML Extension...")) { if(ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) { ActiveRMLExtension.RMLStatus = RMLExtensionStatus.InProgress; ColorParametersVewVM.SaveColorParameters -= UpdateStatus; TestResultsViewVM.SaveTestResults -= UpdateStatus; } ActiveRMLExtension.LastUpdated = DateTime.UtcNow; ActiveRML.LastUpdated = DateTime.UtcNow; await _active_context.SaveChangesAsync(); // _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlSaved, _authentication.CurrentUser, _rmlBeforeSave.Name, _rmlBeforeSave, rmlAfter, "RML saved using Machine Studio."); RefreshView(ActiveRMLExtension.Guid, ActiveRML.Guid); } } catch (Exception ex) { LogManager.Log(ex, $"Error saving RML Extension of RML{ActiveRML.Name}"); _notification.ShowError($"An error occurred while trying to save the current RML Extension.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } #endregion } }