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

import "io_base.jncx"
import "io_mon.jncx"
import "io_SerialMon.jnc"
import "doc_Plugin.jnc"

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

class SerialMonSession: doc.Session
{
protected:
	enum State
	{
		Closed,
		Opened,
	}

	enum ActionId
	{
		Capture,
		_Count,
	}

	enum IconId
	{
		Capture,
		StopCapture,
		_Count,
	}

	enum StatusPaneId
	{
		State,
		_Count,
	}

protected:
	// serial port

	State bindable m_state;
	io.SerialMon m_serialMon;
	SerialLogFilter m_logFilter;
	char const* m_portName;

	// 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;

	// filter property grid

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

public:
	construct (doc.PluginHost* pluginHost);

	bool capture () throws;
	stopCapture ();

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

protected:
	onCapture ();
	onReadyRead (uint_t syncId);

	createUi ();
	reactor m_uiReactor ();
}

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

SerialMonSession.construct (doc.PluginHost* pluginHost)
{
	basetype.construct (pluginHost);
	pluginHost.m_log.m_representerFunc = representSerialMonLog;
	pluginHost.m_log.attachFilter (m_logFilter);

	m_state = State.Closed;
	m_serialMon.m_onReadyRead += onReadyRead @ pluginHost.m_mainThreadScheduler;

	createUi ();
}

SerialMonSession.createUi ()
{
	// toolbar

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

	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_name, null);

	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	

	m_portProp = io.createSerialPortProperty (
		m_pluginHost.m_propertyGrid,
		"Port",
		"Specify serial port to use",
		portList,
		portCount
		);
	
	// filter 

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

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

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

SerialMonSession.onCapture ()
{
	if (m_state)
		stopCapture ();
	else
		try capture ();
}

bool SerialMonSession.capture () throws
{
	stopCapture ();

	char const* name = m_portCombo.m_currentText;

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

	m_portName = name;
	m_state = State.Opened;
	return true;

catch:
	m_serialMon.close ();

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

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

	writeLog (
		SerialMonLogRecordCode.CaptureStopped,
		m_portName,
		strlen (m_portName) + 1
		);

	m_serialMon.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");
	m_logFilter.m_isControlLineChangedVisible = storage.readBool ("isControlLineChangedVisible");
	m_logFilter.m_isStatusLineChangedVisible = storage.readBool ("isStatusLineChangedVisible");
}

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);
}

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 SerialMonSession.applyProperties () throws
{
	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;
	return true;
}

void SerialMonSession.restoreDefaultProperties ()
{
	m_portProp.m_currentIndex = 0;
	m_settingChangedVisibleProp.m_value = true;
	m_controlLineChangedVisibleProp.m_value = true;
	m_statusLineChangedVisibleProp.m_value = true;
}

SerialMonSession.onReadyRead (uint_t syncId)
{
	if (syncId != m_serialMon.m_syncId)
		return;
		
	io.SerialMonEventParams params;
	try m_serialMon.read (&params);
	
	switch (params.m_eventKind)
	{
	case io.SerialMonEvent.DeviceOpened:
		writeLog (SerialMonLogRecordCode.DeviceOpened);
		break;	

	case io.SerialMonEvent.DeviceClosed:		
		writeLog (SerialMonLogRecordCode.DeviceClosed);
		break;
		
	case io.SerialMonEvent.RxData:
		writeLog (log.StdRecordCode.Rx, params.m_data, params.m_dataSize);
		break;

	case io.SerialMonEvent.TxData:
		writeLog (log.StdRecordCode.Tx, params.m_data, params.m_dataSize);
		break;

	case io.SerialMonEvent.BaudRateChanged:
		writeLog (SerialLogRecordCode.BaudRateChanged, &params.m_baudRate, sizeof (params.m_baudRate));
		break;

	case io.SerialMonEvent.FlowControlChanged:
		writeLog (SerialLogRecordCode.FlowControlChanged, &params.m_flowControl, sizeof (params.m_flowControl));
		break;

	case io.SerialMonEvent.DataBitsChanged:
		writeLog (SerialLogRecordCode.DataBitsChanged, &params.m_dataBits, sizeof (params.m_dataBits));
		break;

	case io.SerialMonEvent.StopBitsChanged:
		writeLog (SerialLogRecordCode.StopBitsChanged, &params.m_stopBits, sizeof (params.m_stopBits));
		break;

	case io.SerialMonEvent.ParityChanged:
		writeLog (SerialLogRecordCode.ParityChanged, &params.m_parity, sizeof (params.m_parity));
		break;

	case io.SerialMonEvent.StatusLineChanged:
		uint_t mask = -1;
		char const* p = $"$(params.m_statusLines; B)$(mask; B)";
		writeLog (SerialLogRecordCode.StatusLineChanged, p, dynamic sizeof (p));
		break;

	case io.SerialMonEvent.DtrChanged:
		writeLog (SerialLogRecordCode.DtrChanged, &params.m_dtr, sizeof (params.m_dtr));
		break;

	case io.SerialMonEvent.RtsChanged:
		writeLog (SerialLogRecordCode.RtsChanged, &params.m_rts, sizeof (params.m_rts));
		break;
	} 
}

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";
}

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