/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include "window.h"
#include "label.h"
#include "timer.h"

#include "taglist.h"
#include "config.h"
#include "network.h"
#include "comport.h"

#include "hangup.h"


typedef enum HangupStateE {
	S_START_HANGUP = 0,
	S_WAITING
} HangupStateT;


static widgetCallback  _done        = NULL;
static WindowT        *_winHangup   = NULL;
static LabelT         *_lblHangup   = NULL;
static TimerT         *_timProgress = NULL;
static HangupStateT    _state       = S_START_HANGUP;


static void timHangupProgress(WidgetT *widget);


void hangupShow(void *nextFunction) {

	_done = (widgetCallback)nextFunction;

	TagItemT uiDetecting[] = {
		T_START,
			T_WINDOW, O(_winHangup),
				T_TITLE, P("Goodbye"),
				T_WIDTH, 200, T_HEIGHT, 100,
				T_LABEL, O(_lblHangup),
					T_X, 41, T_Y, 25,
					T_TITLE, P("Disconnecting!"),
				T_LABEL, T_DONE,
				T_TIMER, O(_timProgress),
					T_EVENT, P(timHangupProgress),
					T_VALUE, 0,
				T_TIMER, T_DONE,
			T_WINDOW, T_DONE,
		T_END
	};

	// We can use a module-global variable instead of widget user data
	// because there will never be more than one disconnect dialog on
	// the screen at a time.
	_state = S_START_HANGUP;

	tagListRun(uiDetecting);
}


static void timHangupProgress(WidgetT *widget) {
	PacketEncodeDataT  encoded = { 0 };
	TimerT            *t       = (TimerT *)widget;

	switch (_state) {
		case S_START_HANGUP:
			// Tell server we're disconnecting.
			encoded.packetType = PACKET_TYPE_CLIENT_SHUTDOWN;
			encoded.control    = PACKET_CONTROL_DAT;
			encoded.channel    = 0;
			encoded.encrypt    = 0;
			packetEncode(__packetThreadData, &encoded, NULL, 0);
			packetSend(__packetThreadData, &encoded);
			// Snooze a bit for the packet to send.
			_state = S_WAITING;
			timerQuarterSecondsSet(t, 3 * 4);
			break;

		case S_WAITING:
			// Shut down packet processing & COM port.
			netPacketHandlerStop();
			comClose(__configData.serialCom - 1);
			timerStop(t);
			// On to the next dialog.
			guiDelete(D(_winHangup));
			_done(NULL);
			break;
	}
}
