/*
    PIP - Platform Independent Primitives
    Remote console viewer
	Copyright (C) 2016  Ivan Pelipenko peri4ko@gmail.com

    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 <http://www.gnu.org/licenses/>.
*/

#include "pip.h"

void key_event(PIKbdListener::KeyEvent key, void * );

PIConsole console(false, key_event);
PIStringList as;
bool selected = false;

void key_event(PIKbdListener::KeyEvent key, void * ) {
	if (key.key < '1' || key.key > '9') return;
	int ind = key.key - '1';
	if (ind < 0 || ind >= as.size_s()) return;
	selected = true;
	console.connectToServer(as[ind]);
}

int main(int argc, char * argv[]) {
	console.enableExitCapture();
	console.listenServers();
	while (!PIKbdListener::exiting) {
		msleep(200);
		if (selected) break;
		console.clearScreen();
		as = console.availableServers();
		if (as.isEmpty()) {
			piCout << "No servers are available!";
		} else {
			piCout << "Select one with numeric key:";
			for (int i = 0; i < as.size_s(); ++i)
				piCout << (i + 1) << as[i];
		}
	}
	if (!selected) return 0;
	//console.clearScreen();
	piCout << "Connecting to" << console.selectedServer() << "...";
	while (!PIKbdListener::exiting) {
		msleep(20);
		if (console.isConnected())
			break;
	}
	if (PIKbdListener::exiting)
		return 0;
	console.start();
	console.waitForFinish();
};
