using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.DI;
using Tango.Integration.Operation;
using Tango.PMR.IFS;
using Tango.PPC.Common;
using Tango.PPC.Common.Connection;
using Tango.PPC.Common.Modules;
using Tango.PPC.Common.Navigation;
using Tango.PPC.UI.Dialogs;
using Tango.PPC.UI.Views;
using Tango.PPC.UI.ViewsContracts;
using Tango.SharedUI;
namespace Tango.PPC.UI.ViewModels
{
///
/// Represents the layout view containing the main menu and all modules.
///
///
public class LayoutViewVM : PPCViewModel
{
private JobHandler _jobHandler;
private bool _resettingDevice;
private DispatcherTimer _date_timer;
///
/// Gets or sets the module loader.
///
[TangoInject]
public IPPCModuleLoader ModuleLoader { get; set; }
#region Classes
public class CartridgeModel : ExtendedObject
{
private IMachineProvider _machineProvider;
private CartridgeStatus _status;
public CartridgeStatus Status
{
get { return _status; }
set { _status = value; PreviousState = _status.State; }
}
public CartridgeState PreviousState { get; set; }
public bool InProgress
{
get { return Status.State == CartridgeState.Filling || Status.State == CartridgeState.Emptying; }
}
public String Message
{
get
{
if (Status.Cartridge.Slot == PMR.Diagnostics.CartridgeSlot.Ink)
{
try
{
int index = Status.Cartridge.Index;
var idsPack = _machineProvider.Machine.Configuration.NoneEmptyIdsPacks.FirstOrDefault(x => x.PackIndex == index);
if (idsPack != null)
{
return $"{idsPack.LiquidType.Name} filling is in progress...";
}
else
{
return "Ink filling is in progress...";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return "Ink filling is in progress...";
}
}
else
{
return "Waste emptying is in progress...";
}
}
}
public Brush Brush
{
get
{
if (Status.Cartridge.Slot == PMR.Diagnostics.CartridgeSlot.Ink)
{
try
{
int index = Status.Cartridge.Index;
var idsPack = _machineProvider.Machine.Configuration.NoneEmptyIdsPacks.FirstOrDefault(x => x.PackIndex == index);
if (idsPack != null)
{
switch (idsPack.LiquidType.Type)
{
case BL.Enumerations.LiquidTypes.Cyan:
return Application.Current.Resources["TangoCyanInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.Magenta:
return Application.Current.Resources["TangoMagentaInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.Yellow:
return Application.Current.Resources["TangoYellowInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.Black:
return Application.Current.Resources["TangoBlackInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.Lubricant:
return Application.Current.Resources["TangoLubricantBrush"] as Brush;
case BL.Enumerations.LiquidTypes.Cleaner:
return Application.Current.Resources["TangoCleanerBrush"] as Brush;
case BL.Enumerations.LiquidTypes.TransparentInk:
return Application.Current.Resources["TangoTransparentInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.LightCyan:
return Application.Current.Resources["TangoLightCyanInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.LightMagenta:
return Application.Current.Resources["TangoLightMagentaInkBrush"] as Brush;
case BL.Enumerations.LiquidTypes.LightYellow:
return Application.Current.Resources["TangoLightYellowInkBrush"] as Brush;
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error generating ink filling brush.");
}
return Application.Current.Resources["TangoPrimaryAccentBrush"] as Brush;
}
else
{
return Application.Current.Resources["TangoWasteBrush"] as Brush;
}
}
}
public CartridgeModel(IMachineProvider machineProvider)
{
_machineProvider = machineProvider;
Status = new CartridgeStatus();
}
public void Invalidate()
{
RaisePropertyChanged(nameof(InProgress));
RaisePropertyChanged(nameof(Status));
}
}
#endregion
#region Properties
private bool _isMenuOpened;
///
/// Gets or sets a value indicating whether the side menu is opened.
///
public bool IsMenuOpened
{
get { return _isMenuOpened; }
set
{
_isMenuOpened = value; RaisePropertyChangedAuto();
if (!_isMenuOpened)
{
IsPowerOpened = false;
}
}
}
private bool _isNotificationsOpened;
///
/// Gets or sets a value indicating whether to display all notifications.
///
public bool IsNotificationsOpened
{
get { return _isNotificationsOpened; }
set
{
_isNotificationsOpened = value; RaisePropertyChangedAuto();
}
}
private bool _isPowerOpened;
///
/// Gets or sets a value indicating whether the power area is opened.
///
public bool IsPowerOpened
{
get { return _isPowerOpened; }
set { _isPowerOpened = value; RaisePropertyChangedAuto(); }
}
private bool _isInkFillingOrWasteEmptying;
///
/// Gets or sets a value indicating whether ink filling or waste emptying is active.
///
public bool IsInkFillingOrWasteEmptying
{
get { return _isInkFillingOrWasteEmptying; }
set { _isInkFillingOrWasteEmptying = value; RaisePropertyChangedAuto(); }
}
private List _cartridges;
public List Cartridges
{
get { return _cartridges; }
set { _cartridges = value; RaisePropertyChangedAuto(); }
}
private DateTime _currentDateTime;
///
/// Gets or sets the current date time.
///
public DateTime CurrentDateTime
{
get { return _currentDateTime; }
set { _currentDateTime = value; RaisePropertyChangedAuto(); }
}
#endregion
#region Commands
///
/// Gets or sets the module navigation command.
///
public RelayCommand ModuleNavigationCommand { get; set; }
///
/// Gets or sets the menu or back command.
///
public RelayCommand MenuOrBackCommand { get; set; }
///
/// Gets or sets the home command.
///
public RelayCommand HomeCommand { get; set; }
///
/// Gets or sets the notifications area pressed command.
///
public RelayCommand NotificationsAreaPressedCommand { get; set; }
///
/// Gets or sets the stop printing command.
///
public RelayCommand StopPrintingCommand { get; set; }
///
/// Gets or sets the sign-out command.
///
public RelayCommand SignOutCommand { get; set; }
///
/// Gets or sets the update command.
///
public RelayCommand UpdateCommand { get; set; }
///
/// Gets or sets the power command.
///
public RelayCommand PowerCommand { get; set; }
///
/// Gets or sets the restart application command.
///
public RelayCommand RestartApplicationCommand { get; set; }
///
/// Gets or sets the power off command.
///
public RelayCommand PowerOffCommand { get; set; }
///
/// Gets or sets the reset command.
///
public RelayCommand ResetCommand { get; set; }
///
/// Gets or sets the stand by command.
///
public RelayCommand StandByCommand { get; set; }
#endregion
#region Constructors
///
/// Initializes a new instance of the class.
///
public LayoutViewVM()
{
ModuleNavigationCommand = new RelayCommand(NavigateToModule);
HomeCommand = new RelayCommand(NavigateHome);
MenuOrBackCommand = new RelayCommand(OpenMenuOrNavigateBack);
NotificationsAreaPressedCommand = new RelayCommand(OpenFirstNotificationOrDisplayAll);
StopPrintingCommand = new RelayCommand(StopPrinting);
SignOutCommand = new RelayCommand(SignOut);
UpdateCommand = new RelayCommand(UpdateMachine);
PowerCommand = new RelayCommand(OpenPowerOptions);
RestartApplicationCommand = new RelayCommand(RestartApplication);
PowerOffCommand = new RelayCommand(PowerOffMachine, () => MachineProvider.MachineOperator.Status != MachineStatuses.Disconnected);
ResetCommand = new RelayCommand(ResetMachine, () => MachineProvider.MachineOperator.Status != MachineStatuses.Disconnected);
StandByCommand = new RelayCommand(StandBy, () => MachineProvider.MachineOperator.CanPrint);
_date_timer = new DispatcherTimer();
_date_timer.Interval = TimeSpan.FromSeconds(1);
_date_timer.Tick += _date_timer_Tick;
_date_timer.Start();
}
#endregion
#region Private Methods
private async void OpenPowerOptions()
{
IsPowerOpened = true;
if (BuildProvider.IsEureka)
{
PowerEurekaViewVM vm = new PowerEurekaViewVM();
vm = await NotificationProvider.ShowDialog(vm);
if (!vm.DialogResult) return;
switch(vm.PowerAction)
{
case PowerEurekaViewVM.PowerActionEnum.TurnOff:
if(MachineProvider.MachineOperator.Status != MachineStatuses.Disconnected)
PowerOffMachine();
return;
case PowerEurekaViewVM.PowerActionEnum.StandBy:
if (MachineProvider.MachineOperator.CanPrint)
StandBy();
return;
case PowerEurekaViewVM.PowerActionEnum.RestartT:
RestartApplication();
return;
case PowerEurekaViewVM.PowerActionEnum.Restart:
if (MachineProvider.MachineOperator.Status != MachineStatuses.Disconnected)
ResetMachine();
return;
default:
return;
}
}
}
///
/// Stops the printing.
///
private void StopPrinting()
{
LogManager.Log("Stop printing layout command pressed!");
if (_jobHandler != null)
{
_jobHandler.Cancel();
}
}
///
/// Opens the menu or navigate back.
///
private void OpenMenuOrNavigateBack()
{
if (NavigationManager.CanNavigateBack)
{
LogManager.Log("Back command pressed.");
NavigationManager.NavigateBack();
}
else
{
LogManager.Log("Menu command pressed.");
IsMenuOpened = true;
}
}
///
/// Handles the module navigation command.
///
/// Name of the module.
private void NavigateToModule(string moduleName)
{
LogManager.Log("Navigate to module command pressed.");
IsMenuOpened = false;
NavigationManager.NavigateTo(moduleName);
}
///
/// Handles the home command.
///
private void NavigateHome()
{
LogManager.Log("Navigate home command pressed.");
IsMenuOpened = false;
NavigationManager.NavigateTo(NavigationView.HomeModule);
}
///
/// Represents an event that is raised when the sign-out operation is complete.
///
private void SignOut()
{
LogManager.Log("SignOut command pressed.");
AuthenticationProvider.LogOut();
IsMenuOpened = false;
}
///
/// Opens the first notification or display all.
///
private void OpenFirstNotificationOrDisplayAll()
{
if (NotificationProvider.NotificationItems.Count == 1)
{
//Open first
}
else
{
IsNotificationsOpened = true;
}
}
///
/// Restarts the application.
///
private async void RestartApplication()
{
if (await NotificationProvider.ShowQuestion("Are you sure you want to restart the application?"))
{
ApplicationManager.Restart();
}
}
///
/// Powers off the machine.
///
private async void PowerOffMachine()
{
IsMenuOpened = false;
if (await NotificationProvider.ShowQuestion("Are you sure you wish to turn off the machine?"))
{
try
{
await MachineProvider.MachineOperator.PowerDown();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error triggering power down.");
await NotificationProvider.ShowError(ex.FlattenMessage());
}
}
}
///
/// Resets the machine.
///
private async void ResetMachine()
{
IsMenuOpened = false;
if (!await NotificationProvider.ShowQuestion("Are you sure you want to reset the machine?")) return;
try
{
_resettingDevice = true;
ResetCommand.RaiseCanExecuteChanged();
await MachineProvider.MachineOperator.Reset();
await NotificationProvider.ShowInfo("Machine was successfully restarted.");
}
catch (Exception ex)
{
await NotificationProvider.ShowError(ex.FlattenMessage());
}
finally
{
_resettingDevice = false;
ResetCommand.RaiseCanExecuteChanged();
}
}
private async void StandBy()
{
IsMenuOpened = false;
try
{
LogManager.Log("Executing stand-by command.");
await MachineProvider.MachineOperator.StandBy();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error switching to stand-by mode.");
await NotificationProvider.ShowError($"Error switching to stand-by mode.\n{ex.FlattenMessage()}");
}
}
private void UpdateMachine()
{
if (MachineProvider.MachineOperator.IsPrinting)
{
NotificationProvider.ShowInfo("Cannot perform a machine update while the machine is dyeing.");
return;
}
NavigationManager.NavigateTo(NavigationView.MachineUpdateView);
TangoIOC.Default.GetInstance().CheckForUpdates();
IsMenuOpened = false;
}
#endregion
#region Override Methods
///
/// Called when the application has been started.
///
public override void OnApplicationStarted()
{
base.OnApplicationStarted();
MachineProvider.MachineOperator.PrintingStarted += MachineOperator_PrintingStarted;
MachineProvider.MachineOperator.InkFillingStatusChanged += MachineOperator_InkFillingStatusChanged;
}
private void MachineOperator_InkFillingStatusChanged(object sender, InkFillingStatusChangedEventArgs e)
{
if (Cartridges == null)
{
Cartridges = MachineProvider.MachineOperator.InkFillingStatus.CartridgesStatuses.Select(x => new CartridgeModel(MachineProvider) { Status = x }).ToList();
}
else
{
foreach (var cartridgeStatus in e.Status.CartridgesStatuses)
{
var model = Cartridges.SingleOrDefault(x => x.Status == cartridgeStatus);
if (model != null)
{
if (cartridgeStatus != null)
{
if ((cartridgeStatus.State == CartridgeState.Error || cartridgeStatus.State == CartridgeState.EmpyingFailed || cartridgeStatus.State == CartridgeState.FillingFailed) && (model.PreviousState != CartridgeState.Error && model.PreviousState != CartridgeState.FillingFailed && model.PreviousState != CartridgeState.EmpyingFailed))
{
NotificationProvider.ShowError(cartridgeStatus.Message);
}
if ((cartridgeStatus.State == CartridgeState.EmptyingCompleted || cartridgeStatus.State == CartridgeState.FillingCompleted)
&&
(model.PreviousState != CartridgeState.EmptyingCompleted && model.PreviousState != CartridgeState.FillingCompleted))
{
NotificationProvider.ShowSuccess(cartridgeStatus.Message);
}
}
model.Status = cartridgeStatus;
}
}
}
foreach (var cartridgeModel in Cartridges)
{
cartridgeModel.Invalidate();
}
IsInkFillingOrWasteEmptying = Cartridges.Any(x => x.Status.State == CartridgeState.Filling || x.Status.State == CartridgeState.Emptying);
}
///
/// Called when the instance of IPPCView is available.
///
public override void OnViewAttached()
{
}
public override void OnApplicationReady()
{
base.OnApplicationReady();
MachineProvider.MachineOperator.StatusChanged += MachineOperator_StatusChanged;
}
private void MachineOperator_StatusChanged(object sender, MachineStatuses e)
{
InvokeUI(() =>
{
PowerOffCommand.RaiseCanExecuteChanged();
ResetCommand.RaiseCanExecuteChanged();
StandByCommand.RaiseCanExecuteChanged();
});
}
#endregion
#region Public Methods
///
/// Toggles the application technician mode.
///
public void ToggleTechnicianMode()
{
if (!ApplicationManager.IsInTechnicianMode)
{
ApplicationManager.EnterTechnicianMode();
}
else
{
ApplicationManager.ExitTechnicianMode();
}
}
#endregion
#region Event Handlers
private void _date_timer_Tick(object sender, EventArgs e)
{
CurrentDateTime = DateTime.Now;
}
///
/// Handles the PrintingStarted event of the MachineOperator.
///
/// The source of the event.
/// The instance containing the event data.
private void MachineOperator_PrintingStarted(object sender, PrintingEventArgs e)
{
_jobHandler = e.JobHandler;
}
#endregion
}
}