//..............................................................................
//
// Serial Monitor session
//

import "io_base.jncx"
import "io_devmon.jncx"
import "io_DeviceMonitor.jnc"
import "std_Buffer.jnc"
import "doc_Plugin.jnc"

//..............................................................................

class SerialMonSession: doc.Session
{
protected:
	enum Defaults
	{
		PendingNotifySizeLimit = 1 * 1024 * 1024, // 1MB
	}

	enum State
	{
		Closed,
		Opened,
	}

	enum ActionId
	{
		Refresh,
		Capture,
		_Count,
	}

	enum IconId
	{
		Capture,
		StopCapture,
		_Count,
	}

	enum StatusPaneId
	{
		State,
		_Count,
	}

protected:
	// serial port

	State bindable m_state;
	SerialMonitor m_monitor;
	SerialLogFilter m_logFilter;

	// toolbar, status bar & menu

	gui.Action* m_actionTable [ActionId._Count];
	gui.Icon* m_iconTable [IconId._Count];
	gui.StatusPane* m_statusPaneTable [StatusPaneId._Count];
	gui.ComboBox* m_portCombo;

	// serial mon property grid

	gui.EnumProperty* m_portProp;
	io.BufferPropertySet m_bufferPropertySet;
	gui.IntProperty* m_pendingNotifySizeLimitProp;

	// filter property grid

	gui.BoolProperty* m_settingChangedVisibleProp;
	gui.BoolProperty* m_controlLineChangedVisibleProp;
	gui.BoolProperty* m_statusLineChangedVisibleProp;

public:
	construct (doc.PluginHost* pluginHost);

	bool errorcode capture ();
	close ();

	override void load (doc.Storage* storage);
	override void save (doc.Storage* storage);
	override void updateProperties ();
	override bool errorcode applyProperties ();
	override void restoreDefaultProperties ();

protected:
	onRefresh ();

	onCapture ()
	{
		m_state ? close () : try capture ();
	}

	onPortComboEnter ()
	{
		try capture ();
	}

	createUi ();
	reactor m_uiReactor ();
}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

SerialMonSession.construct (doc.PluginHost* pluginHost)
{
	basetype.construct (pluginHost);
	m_monitor.construct (this);

	pluginHost.m_log.attachRepresenter (representSerialMonLog);
	pluginHost.m_log.attachFilter (m_logFilter);

	m_state = State.Closed;

	createUi ();
}

SerialMonSession.createUi ()
{
	// toolbar

	m_pluginHost.m_toolBar.addLabel ("Port:");
	m_portCombo = m_pluginHost.m_toolBar.addComboBox (-1);
	m_portCombo.m_isEditable = true;
	m_portCombo.m_onEnter += onPortComboEnter;

	size_t portCount;
	io.SerialPortDesc const* portList = io.createSerialPortDescList (&portCount);
	io.SerialPortDesc const* port = portList;
	for (; port; port = port.m_next)
		m_portCombo.addItem (port.m_deviceName, null);

	m_actionTable [ActionId.Refresh] = createAction ("Refresh port list", "images/refresh.png");
	m_actionTable [ActionId.Refresh].m_onTriggered += onRefresh;

	m_iconTable [IconId.Capture] = new gui.Icon ("images/capture.png");
	m_iconTable [IconId.StopCapture] = new gui.Icon ("images/pause.png");

	m_actionTable [ActionId.Capture] = createAction ("Capture", m_iconTable [IconId.Capture]);
	m_actionTable [ActionId.Capture].m_onTriggered += onCapture;

	// status bar

	m_statusPaneTable [StatusPaneId.State] = m_pluginHost.m_statusBar.addPane (, 80);

	// property grid

	gui.GroupProperty* group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"Device",
		"Serial port monitor target device settings"
		);

	m_portProp = io.createSerialPortProperty (
		m_pluginHost.m_propertyGrid,
		group,,
		"Port",
		"Specify serial port to monitor",
		portList,
		portCount
		);

	group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"Buffering & compatibility",
		"Advanced options controlling performance, throughtput and compatibility"
		);

	m_bufferPropertySet.createProperties (
		m_pluginHost.m_propertyGrid,
		group,,
		io.BufferPropertySet.PropertyId.ReadParallelism |
		io.BufferPropertySet.PropertyId.ReadBufferSize |
		io.BufferPropertySet.PropertyId.ReadBlockSize |
		io.BufferPropertySet.PropertyId.NotifyReadBufferFull
		);

	m_pendingNotifySizeLimitProp = m_pluginHost.m_propertyGrid.createIntProperty (
		group,,
		"Pending notifaction limit",
		"Set the maximum size of kernel notification queue (exceeding notification will be dropped)"
		);

	m_bufferPropertySet.m_readBlockSizeProp.m_minValue = 1024;
	m_bufferPropertySet.m_readBufferSizeProp.m_minValue = 1024;
	m_pendingNotifySizeLimitProp.m_minValue = 1024;
	m_pendingNotifySizeLimitProp.m_spinBoxStep = 1024; // 1KB

	// filter

	group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"Log filter",
		"Specify which unwanted log messages to filter out"
		);

	m_settingChangedVisibleProp = m_pluginHost.m_propertyGrid.createBoolProperty (
		group,,
		"Show setting changes",
		"Display setting change log records (or filter them out)"
		);

	m_controlLineChangedVisibleProp = m_pluginHost.m_propertyGrid.createBoolProperty (
		group,,
		"Show control line changes",
		"Display control line change log records (or filter them out)"
		);

	m_statusLineChangedVisibleProp = m_pluginHost.m_propertyGrid.createBoolProperty (
		group,,
		"Show status line changes",
		"Display status line change log records (or filter them out)"
		);

	m_uiReactor.start ();
}

SerialMonSession.onRefresh ()
{
	char const* name = m_portCombo.m_currentText;
	m_portCombo.clear ();

	size_t portCount;
	io.SerialPortDesc const* portList = io.createSerialPortDescList (&portCount);
	io.SerialPortDesc const* port = portList;
	for (; port; port = port.m_next)
		m_portCombo.addItem (port.m_deviceName, null);

	m_portCombo.m_editText = name; // preserve current text
	m_portCombo.adjustSizeToContents ();

	io.updateSerialPortProperty (m_portProp, portList, portCount);
}

bool errorcode SerialMonSession.capture ()
{
	close ();
	startSession ();

	char const* name = m_portCombo.m_currentText;

	m_monitor.applyProperties (m_bufferPropertySet, m_pendingNotifySizeLimitProp.m_value);
	m_monitor.capture (name);

	writeLog (SerialMonLogRecordCode.CaptureStarted, name, strlen (name));

	m_state = State.Opened;
	return true;

catch:
	m_monitor.close ();

	std.Error const* error = std.getLastError ();
	writeLog (
		SerialMonLogRecordCode.CaptureError,
		error,
		error.m_size
		);
	return false;
}

SerialMonSession.close ()
{
	if (m_state != State.Opened)
		return;

	writeLog (SerialMonLogRecordCode.CaptureStopped);

	m_monitor.close ();
	m_state = State.Closed;
}

void SerialMonSession.load (doc.Storage* storage)
{
	m_portCombo.m_editText = storage.readString ("portName");
	m_logFilter.m_isSettingChangedVisible = storage.readBool ("isSettingChangedVisible", true);
	m_logFilter.m_isControlLineChangedVisible = storage.readBool ("isControlLineChangedVisible", true);
	m_logFilter.m_isStatusLineChangedVisible = storage.readBool ("isStatusLineChangedVisible", true);
	m_pendingNotifySizeLimitProp.m_value = storage.readInt ("pendingNotifySizeLimit", Defaults.PendingNotifySizeLimit);

	m_bufferPropertySet.load (storage);
	m_monitor.setReadBufferSize (m_bufferPropertySet.m_readBufferSizeProp.m_value);
}

void SerialMonSession.save (doc.Storage* storage)
{
	storage.writeString ("portName", m_portCombo.m_editText);
	storage.writeBool ("isSettingChangedVisible", m_logFilter.m_isSettingChangedVisible);
	storage.writeBool ("isControlLineChangedVisible", m_logFilter.m_isControlLineChangedVisible);
	storage.writeBool ("isStatusLineChangedVisible", m_logFilter.m_isStatusLineChangedVisible);
	storage.writeInt ("pendingNotifySizeLimit", m_pendingNotifySizeLimitProp.m_value);

	m_bufferPropertySet.save (storage);
}

void SerialMonSession.updateProperties ()
{
	m_portProp.m_currentIndex = m_portCombo.m_currentIndex;
	m_settingChangedVisibleProp.m_value = m_logFilter.m_isSettingChangedVisible;
	m_controlLineChangedVisibleProp.m_value = m_logFilter.m_isControlLineChangedVisible;
	m_statusLineChangedVisibleProp.m_value = m_logFilter.m_isStatusLineChangedVisible;
}

bool errorcode SerialMonSession.applyProperties ()
{
	m_portCombo.m_currentIndex = m_portProp.m_currentIndex;
	m_logFilter.m_isSettingChangedVisible = m_settingChangedVisibleProp.m_value;
	m_logFilter.m_isControlLineChangedVisible = m_controlLineChangedVisibleProp.m_value;
	m_logFilter.m_isStatusLineChangedVisible = m_statusLineChangedVisibleProp.m_value;

	if (m_state != State.Opened)
		return true;

	m_monitor.applyProperties (m_bufferPropertySet, m_pendingNotifySizeLimitProp.m_value);
	return true;
}

void SerialMonSession.restoreDefaultProperties ()
{
	m_settingChangedVisibleProp.m_value = true;
	m_controlLineChangedVisibleProp.m_value = true;
	m_statusLineChangedVisibleProp.m_value = true;
	m_pendingNotifySizeLimitProp.m_value = Defaults.PendingNotifySizeLimit;

	m_bufferPropertySet.restoreDefaults ();
}

reactor SerialMonSession.m_uiReactor ()
{
	m_title = $"Mon $(m_portCombo.m_currentText)";
	m_actionTable [ActionId.Capture].m_text = m_state ? "Stop capture" : "Capture";
	m_actionTable [ActionId.Capture].m_icon = m_iconTable [m_state ? IconId.StopCapture : IconId.Capture];
	m_statusPaneTable [StatusPaneId.State].m_text = m_state ? "Capturing" : "Closed";
}

//..............................................................................
