/*
    PIP - Platform Independent Primitives
    Remote console viewer
    Copyright (C) 2015  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 "picli.h"
#include "pisystemmonitor.h"
#include "pisysteminfo.h"
#include "file_manager.h"
#include "daemon.h"
#include "shared.h"

class _Init {
public:
	_Init() {srand(PISystemTime::current().toMicroseconds());}
};
_Init _pisd_init;

PIScreen screen(false);
PISystemMonitor sys_mon;
Daemon daemon_;
FileManager file_manager;


class MainMenu: public PITimer {
	PIOBJECT_SUBCLASS(MainMenu, PITimer)
public:
	MainMenu() {
		cur_peer = -1;
		TileSimple * tile = new TileSimple("title");
		tile->content << TileSimple::Row("pisd (PI System Daemon, PIP version " + PIPVersion() + ")", CellFormat(Black, Transparent));
		tile->content << TileSimple::Row("This daemon: \"" + daemon_.thisDaemonName() + "\"", CellFormat(Black, Transparent));
		tile->back_format.color_back = Yellow;
		tile->size_policy = Fixed;
		screen.rootTile()->addTile(tile);
		
		PIScreenTile * center = new PIScreenTile("center");
		center->back_format.color_back = Cyan;
		center->size_policy = Expanding;
		center->setMargins(2, 2, 1, 1);
		screen.rootTile()->addTile(center);
		
		PIScreenTile * mt = tmenu = menuTile();
		mt->show(); mt->name() = "main menu";
		center->addTile(mt); mtiles << mt;
		
		mt = tinfo = infoTile();
		mt->hide(); mt->name() = "local info";
		center->addTile(mt); mtiles << mt;
		
		mt = tfm = file_manager.tile();
		mt->hide(); mt->name() = "file manager";
		center->addTile(mt); mtiles << mt;
		
		mt = tdaemon = daemon_.tile();
		mt->hide(); mt->name() = "daemon";
		center->addTile(mt); mtiles << mt;

		mt = tpeer = peerTile();
		mt->hide(); mt->name() = "peer info";
		center->addTile(mt); mtiles << mt;
		
		TilePICout * outt = new TilePICout();
		outt->size_policy = PIScreenTypes::Expanding;
		screen.rootTile()->addTile(outt);
		
		CONNECTU(&screen, tileEvent, this, tileEvent)
		CONNECTU(&screen, keyPressed, this, keyEvent)
		CONNECTU(&file_manager, menuRequest, this, menuRequest)
		CONNECTU(&daemon_, menuRequest, this, menuRequest)
		start(10);
	}
	PIScreenTile * menuTile() {
		TileList * ret = new TileList();
		ret->content << TileList::Row("Show local info", CellFormat());
		ret->content << TileList::Row("Local file manager", CellFormat());
		ret->content << TileList::Row("Connect to another daemon", CellFormat());
		ret->content << TileList::Row("Peer info", CellFormat());
		ret->content << TileList::Row("Peer reinit", CellFormat());
		ret->content << TileList::Row("Exit", CellFormat());
		ret->selection_mode = TileList::NoSelection;
		return ret;
	}
	PIScreenTile * infoTile() {
		TileSimple * ret = new TileSimple();
		ret->content << TileSimple::Row("Exec command: " + PISystemInfo::instance()->execCommand, CellFormat());
		ret->content << TileSimple::Row(" Executed on  " + PISystemInfo::instance()->execDateTime.toString(), CellFormat());
		ret->content << TileSimple::Row("    Hostname: " + PISystemInfo::instance()->hostname, CellFormat());
		ret->content << TileSimple::Row("    Username: " + PISystemInfo::instance()->user, CellFormat());
		ret->content << TileSimple::Row("     OS name: " + PISystemInfo::instance()->OS_name, CellFormat());
		ret->content << TileSimple::Row("  OS version: " + PISystemInfo::instance()->OS_version, CellFormat());
		ret->content << TileSimple::Row("Architecture: " + PISystemInfo::instance()->architecture, CellFormat());
		ret->content << TileSimple::Row("   CPU count: " + PIString::fromNumber(PISystemInfo::instance()->processorsCount), CellFormat());
		return ret;
	}
	PIScreenTile * peerTile() {
		PIScreenTile* ret = new PIScreenTile();
		TileSimple * htl = new TileSimple();
		htl->size_policy = PIScreenTypes::Fixed;
		ret->direction = PIScreenTypes::Vertical;
		htl->content << TileSimple::Row("Peer: " + daemon_.name() + " | " + daemon_.selfInfo().name, CellFormat(PIScreenTypes::Default, PIScreenTypes::Default, PIScreenTypes::Bold));
		addrs_tl = new TileList();
		peers_tl = new TileList();
		peerinfo_tl = new TileSimple();
		peermap_tl = new TileList();
		peerinfo_tl->size_policy = PIScreenTypes::Fixed;
		ret->addTile(htl);
		ret->addTile(peers_tl);
		ret->addTile(peerinfo_tl);
		ret->addTile(addrs_tl);
		ret->addTile(peermap_tl);
		updatePeerInfo();
		return ret;
	}
	void updatePeerInfo() {
		bool pm = daemon_.lockedPeers();
		screen.lock();
		daemon_.lock();
		peers_tl->content.clear();
		addrs_tl->content.clear();
		peerinfo_tl->content.clear();
		peermap_tl->content.clear();
		peers_tl->content << TileList::Row("this | 0 | 0 | " + PIString::fromNumber(daemon_.allPeers().size_s()) + 
											" [em = " + PIString::fromBool(daemon_.lockedEth()) + ", "
											"pm = " + PIString::fromBool(pm) + "]", CellFormat());
		piForeachC(PIPeer::PeerInfo &p , daemon_.allPeers())
			peers_tl->content << TileList::Row(p.name + " | d = " + PIString::fromNumber(p.dist) + 
												" | p = " + PIString::fromNumber(p.ping()) + 
												" | n = " + PIString::fromBool(p.isNeighbour())
												, CellFormat());
		PIPeer::PeerInfo pi = daemon_.selfInfo();
		if (cur_peer >= 0 && cur_peer < daemon_.allPeers().size_s()) pi = daemon_.allPeers()[cur_peer];
		peerinfo_tl->content << TileSimple::Row("Name: " + pi.name, CellFormat());
		peerinfo_tl->content << TileSimple::Row("Addreses: " + PIString::fromNumber(pi.addresses.size()), CellFormat());
		peerinfo_tl->content << TileSimple::Row("Neighbours: " + pi.neighbours.join(", "), CellFormat());
		piForeachC(PIPeer::PeerInfo::Address &a , pi.addresses)
			addrs_tl->content << TileList::Row(a.address +
												" | p = " + PIString::fromNumber(a.ping) + 
												" | a = " + PIString::fromBool(a.isAvailable()),  CellFormat());
		typedef PIPair<PIString, PIVector <PIPeer::PeerInfo* > > PeerPair;
		PIStringList peermap;
		piForeachC(PeerPair &p , daemon_._peerMap()) {
			PIString s = p.first + " | ";
			piForeachCR(PIPeer::PeerInfo * pp, p.second) s += " -> " + pp->name;
			peermap << s;
		}
		piForeachC(PIString &s , peermap)
			peermap_tl->content << TileList::Row(s, CellFormat());
		daemon_.unlock();
		screen.unlock();
	}
    void tick(void* data_, int delimiter) {
		updatePeerInfo();
	}
	EVENT_HANDLER(void, menuRequest) {
		piForeach (PIScreenTile * t, mtiles)
			t->hide();
		tmenu->show();
		tmenu->setFocus();
	}
	EVENT_HANDLER2(void, tileEvent, PIScreenTile *, t, PIScreenTypes::TileEvent, e) {
		if (t == tmenu) {
			if (e.type == TileList::RowPressed) {
				piForeach (PIScreenTile * t, mtiles)
					t->hide();
				switch (e.data.toInt()) {
				case 0: tinfo->show(); break;
				case 1: tfm->show(); break;
				case 2: daemon_.showMainList(); tdaemon->show(); break;
				case 3: tpeer->show(); peers_tl->setFocus(); break;
				case 4: daemon_.reinit(); tmenu->show(); break;
				case 5: PIKbdListener::exiting = true; break;
				}
			}
			return;
		}
		if (t == peers_tl) {
			if (e.type == TileList::RowPressed) {
				cur_peer = e.data.toInt() - 1;
				updatePeerInfo();
			}
			return;
		}
	}
	EVENT_HANDLER1(void, keyEvent, PIKbdListener::KeyEvent, e) {
		if (screen.dialogTile()) return;
		if (tpeer->visible || tinfo->visible)
			if (e.key == PIKbdListener::Esc) menuRequest();
		//piCout << "key" << e.key;
	}
	PIScreenTile * tmenu, * tinfo, * tfm, * tdaemon, * tpeer;
	TileList * peers_tl, * addrs_tl, * peermap_tl;
	TileSimple * peerinfo_tl;
	PIVector<PIScreenTile * > mtiles;
	int cur_peer;
};


int main(int argc, char * argv[]) {
	//piDebug = false;
	PICLI cli(argc, argv);
	//cli.addArgument("");
	sys_mon.startOnSelf();
	screen.enableExitCapture(PIKbdListener::F10);
	MainMenu menu;
	screen.start();
	screen.waitForFinish();
	return 0;
};
