using Common;
using Common.AppSettings;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MultiTerm.Core.Model;
using MultiTerm.Core.Types;
using MultiTerm.Protocols.Model;
namespace MultiTerm.Core.ViewModel;
public partial class SendReceiveViewModel : TerminalViewModel
{
public override TerminalViewType ViewType => TerminalViewType.SendReceive;
#region Observable Properties
///
/// Holds communication data that was received via the communication protocol.
///
[ObservableProperty]
private MultiFormatDataViewModel receivedData;
///
/// Holds communication data that was sent via the communication protocol.
///
[ObservableProperty]
private MultiFormatDataViewModel sentData;
///
/// Model for sendable data.
///
[ObservableProperty]
private MultiFormatString sendableData = new();
#endregion
///
/// Constructor.
///
///
public SendReceiveViewModel(IAppSettingsProvider appSettings, IMessenger messenger, IContext context) : base(appSettings, messenger)
{
// create new Communication data containers
this.receivedData = new(context);
this.sentData = new(context);
}
///
/// Send command.
///
[RelayCommand]
private void Send()
{
// send data
if (this.SendToCommunicationProtocol(this.SendableData.GetBytes()))
{
// add to history
this.AddToSendHistory(this.SendableData);
// clear textbox if send was successful
this.SendableData.Clear();
}
}
protected override void HandleInsertElementFromHistory(object? element)
{
// null element received => insert empty
if (element == null)
{
this.SendableData = new MultiFormatString();
return;
}
// otherwise check type
if(element is not MultiFormatString mfs)
{
throw new Exception($"'{HandleInsertElementFromHistory}()' in {nameof(SendReceiveViewModel)} got wrong type of element. Got Type: {element.GetType()}");
}
// overwrite if type is valid
this.SendableData = mfs;
}
public override void DisplayNewReceivedData(IEnumerable newData)
{
this.ReceivedData!.HandleNewData(newData);
}
public override void DisplayNewSentData(IEnumerable newData)
{
this.SentData!.HandleNewData(newData);
}
protected override void ActOnDataDisplayNewlineSeparatorTypeChanged(NewlineSeparatorType newType)
{
// triggers rearranging the displayed data with the new NewlineSeparatorType
this.ReceivedData!.NewlineSeparator = newType;
this.SentData!.NewlineSeparator = newType;
}
}