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; namespace Tango.MachineStudio.ThreadExtensions.ViewModels { public class MainViewVM : StudioViewModel { private INotificationProvider _notification; private IAuthenticationProvider _authentication; private IActionLogManager _actionLogManager; private RmlsExtensionDTO _rmlExtensionBeforeSave; private ObservablesContext _rmlExtentions_context; private ObservablesContext _active_context; #region properties private ObservableCollection _rmlsExtension; public ObservableCollection RmlsExtensions { get { return _rmlsExtension; } set { _rmlsExtension = value; RaisePropertyChangedAuto(); } } private RmlsExtension _activeRMLExtention; public RmlsExtension ActiveRMLExtention { get { return _activeRMLExtention; } set { _activeRMLExtention = value; RaisePropertyChangedAuto(); } } private RmlsExtension _selectedRMLExtension; public RmlsExtension 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 _yarnColor; public ObservableCollection YarnColor { get { return _yarnColor; } set { _yarnColor = value; RaisePropertyChangedAuto(); } } private ObservableCollection _enduse; public ObservableCollection EndUse { get { return _enduse; } set { _enduse = 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 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 void OnFilterChanged() { RmlExtCollectionView.Refresh(); } private ColorParametersVewVM _colorParametersVewVM; public ColorParametersVewVM ColorParametersVewVM { get { return _colorParametersVewVM; } set { _colorParametersVewVM = value; RaisePropertyChangedAuto(); } } #endregion #region commands public RelayCommand SaveCommand { get; set; } public RelayCommand ManageRmlExtensionCommand { get; set; } public RelayCommand AddRmlExtCommand { get; set; } public RelayCommand RemoveRmlExtensionCommand { get; set; } public RelayCommand CloneRmlExtensionCommand { get; set; } public RelayCommand BackToThreadExtensionViewsCommand { get; set; } private void BackToThreadExtensionViews(object obj) { View.NavigateTo(ThreadExtensionNavigationView.ThreadExtensionsView); LoadRmlExtentions(); } private async void CloneSelectedRmlExtension(object obj) { using (_notification.PushTaskItem("Cloning thread...")) { try { IsFree = false; using (var context = ObservablesContext.CreateDefault()) { RmlsExtension rml_extention = await new RmlExtensionsBuilder(_rmlExtentions_context).Set(SelectedRMLExtension.Guid).WithUser().BuildAsync(); RmlsExtension cloned = new RmlsExtension(); rml_extention.MapPropertiesTo(cloned, MappingFlags.NoReferenceTypes); cloned.Guid = Guid.NewGuid().ToString(); cloned.ID = 0; context.RmlsExtensions.Add(cloned); await context.SaveChangesAsync(); //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlCreated, _authentication.CurrentUser, cloned.Name, cloned, "RML cloned from Machine Studio."); } LoadRmlExtentions(); } catch (Exception ex) { LogManager.Log(ex, "Error cloning thread."); _notification.ShowError($"An error occurred while trying to clone the selected thread\n{ex.Message}"); } finally { IsFree = true; } } } private async void RemoveRmlExtension(object obj) { if (_notification.ShowQuestion(" Are you sure you want to delete the selected RML Extension?")) { using (_notification.PushTaskItem("Removing RML Extension...")) { try { IsFree = false; await SelectedRMLExtension.DeleteCascadeAsync(_rmlExtentions_context); //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlDeleted, _authentication.CurrentUser, SelectedRML.Name, SelectedRML, "RML deleted from Machine Studio."); LoadRmlExtentions(); } catch (Exception ex) { LogManager.Log(ex, $"Error removing selected RML {SelectedRMLExtension?.Name}."); _notification.ShowError($"An error occurred while trying to remove the selected RML Extension.\n{ex.FlattenMessage()}"); LoadRmlExtentions(); } finally { IsFree = true; } } } } #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(() => LoadActiveRMLExtention(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); RemoveRmlExtensionCommand = new RelayCommand(RemoveRmlExtension, () => SelectedRMLExtension != null); CloneRmlExtensionCommand = new RelayCommand(CloneSelectedRmlExtension, () => SelectedRMLExtension != null); AddRmlExtCommand = new RelayCommand(AddNewRmlExtention); } public override void OnApplicationReady() { LoadRmlExtentions(); } #region Loading private async void LoadRmlExtentions() { try { IsFree = false; using (_notification.PushTaskItem("Loading RmlExtentions...")) { if (_rmlExtentions_context != null) _rmlExtentions_context.Dispose(); _rmlExtentions_context = ObservablesContext.CreateDefault(); RmlsExtensions = await new RMLExtentionsCollectionBuilder(_rmlExtentions_context).SetAll().WithUser().WithYarnProperties().BuildAsync(); RmlExtCollectionView = CollectionViewSource.GetDefaultView(RmlsExtensions); RmlExtCollectionView.SortDescriptions.Add(new SortDescription(nameof(Rml.LastUpdated), ListSortDirection.Descending)); RmlExtCollectionView.Filter = (rml) => { RmlsExtension r = rml as RmlsExtension; 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.YarnBrand.ToObservableCollection(); YarnColor = _active_context.YarnColor.ToObservableCollection(); EndUse = _active_context.YarnEndUse.ToObservableCollection(); Family = _active_context.YarnFamily.ToObservableCollection(); Geometry = _active_context.YarnGeometry.ToObservableCollection(); GlossLevel = _active_context.YarnGlossLevel.ToObservableCollection(); Group = _active_context.YarnGroup.ToObservableCollection(); Manufacturer = _active_context.YarnManufacturer.ToObservableCollection(); Materials = _active_context.YarnMaterials.ToObservableCollection(); SubFamilies = _active_context.YarnSubFamily.ToObservableCollection(); Texturing = _active_context.YarnTexturing.ToObservableCollection(); YarnTypes = _active_context.YarnType.ToObservableCollection(); IndustrySector = _active_context.YarnIndustrysector.ToObservableCollection(); } private async void AddNewRmlExtention(object obj) { using (_notification.PushTaskItem("Creating new RML Extension...")) { IsFree = false; if (_active_context != null) { _active_context.Dispose(); } _active_context = ObservablesContext.CreateDefault(); LoadRmlProperties(); RmlsExtension rml_extention = new RmlsExtension(); rml_extention.Created = DateTime.UtcNow; rml_extention.UserGuid = _authentication.CurrentUser.Guid; rml_extention.YarnManufacturer = Manufacturer.FirstOrDefault(); rml_extention.YarnBrand = Brands.FirstOrDefault(); rml_extention.Country = null; rml_extention.YarnEndUse = EndUse.FirstOrDefault(); rml_extention.YarnApplications = 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.YarnGeometry = Geometry.FirstOrDefault(); rml_extention.YarnColor = YarnColor.FirstOrDefault(); rml_extention.YarnGlossLevel = GlossLevel.FirstOrDefault(); rml_extention.LinearDensity = 0; rml_extention.YarnUnit = YarnUnits.DTEX; rml_extention.YarnPlies = Plies.P1; rml_extention.FilamentCount = 0; rml_extention.TwistTpm = 0; rml_extention.YarnTwistDirections = TwistDirections.S; 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"; _active_context.RmlsExtensions.Add(rml_extention); await _active_context.SaveChangesAsync(); //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlCreated, _authentication.CurrentUser, rml.Name, rml, "Rml created using Machine Studio."); ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); LoadActiveRMLExtention(rml_extention.Guid); IsFree = true; } } private async void LoadActiveRMLExtention(String guid) { using (_notification.PushTaskItem("Loading RML Extension...")) { try { IsFree = false; if (_active_context != null) { _active_context.Dispose(); } _active_context = ObservablesContext.CreateDefault(); LoadRmlProperties(); ActiveRMLExtention = await new RmlExtensionsBuilder(_active_context) .Set(guid) .WithUser() .BuildAsync(); ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); ColorParametersVewVM.LoadColorParameters(guid); View.NavigateTo(ThreadExtensionNavigationView.ThreadExtentionView); 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) { try { IsFree = false; //if (_active_context != null) //{ // _active_context.Dispose(); //} //_active_context = ObservablesContext.CreateDefault(); LoadRmlProperties(); ActiveRMLExtention = 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 the selected thread.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } #endregion private async void Save() { IsFree = false; try { using (_notification.PushTaskItem("Saving RML Extension...")) { ActiveRMLExtention.LastUpdated = DateTime.UtcNow; ColorParametersVewVM.Save(); var rmlExtensionAfter = RmlsExtensionDTO.FromObservable(ActiveRMLExtention); await _active_context.SaveChangesAsync(); //ColorParametersVewVM.LoadColorParameters(ActiveRMLExtention.Guid); // _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlSaved, _authentication.CurrentUser, _rmlBeforeSave.Name, _rmlBeforeSave, rmlAfter, "RML saved using Machine Studio."); _rmlExtensionBeforeSave = rmlExtensionAfter; RefreshView(SelectedRMLExtension.Guid); } } catch (Exception ex) { LogManager.Log(ex, $"Error saving RML Extension {ActiveRMLExtention.Name}"); _notification.ShowError($"An error occurred while trying to save the current RML Extension.\n{ex.FlattenMessage()}"); } finally { IsFree = true; } } } }