// No touchy!
include("json2.js");
include("OOG.js");
include("gambling.js");
include("craftingsystem.js");
include("common/misc.js");
include("common/util.js");

var i, j, gameInfo, joinInfo, gameStart, ingame, handle,
	gameCount = DataFile.getStats().runs + 1,
	lastGameStatus = "ready",
	LevelLeader = "",
	lastGame = [];

if (!FileTools.exists("data/" + me.profile + ".json")) {
	DataFile.create();
}

function ReceiveCopyData(mode, msg) {
	var obj;

	switch (msg) {
	case "Handle":
		handle = mode;

		break;
	}

	switch (mode) {
	case 1: // JoinInfo
		//print("Got Join Info");

		joinInfo = JSON.parse(msg);

		break;
	case 2: // Game info
		print("Recieved Game Info");

		gameInfo = JSON.parse(msg);

		break;
	case 3: // Game request
		// Don't let others join mule/torch/key/gold drop game
		if (AutoMule.inGame || Gambling.inGame || TorchSystem.inGame || CraftingSystem.inGame) {
			break;
		}

		if (gameInfo) {
			obj = JSON.parse(msg);

			D2Bot.joinMe(obj.profile, me.gamename || "", "", me.gamepassword || "", me.gameReady ? "yes" : "no");
		}

		break;
	case 4:
		// Heartbeat ping
		if (msg === "pingreq") {
			sendCopyData(null, me.windowtitle, 4, "pingrep");
		}

		break;
	}
}

function timer (tick) {
	return " (" + new Date(getTickCount() - tick).toISOString().slice(11, -5) + ")";
}

function main () {
	debugLog(me.profile);
	addEventListener('copydata', ReceiveCopyData);

	while (!handle) {
		delay(100);
	}

	DataFile.updateStats("handle", handle);
	D2Bot.init();
	load("tools/heartbeat.js");

	while (!gameInfo) {
		D2Bot.requestGameInfo();
		delay(500);
	}

	if (gameInfo.error) {
		//D2Bot.retrieve();
		delay(200);
		
		if (!!DataFile.getStats().debugInfo) {
			gameInfo.crashInfo = DataFile.getStats().debugInfo;
			D2Bot.printToConsole("Crash Info: Script: " + JSON.parse(gameInfo.crashInfo).currScript + " Area: " + JSON.parse(gameInfo.crashInfo).area, 10);
		}
		ControlAction.timeoutDelay("Crash Delay", 3000);
		D2Bot.updateRuns();
	}
	D2Bot.store(JSON.stringify({currScript: "none", area: "out of game"}));
	DataFile.updateStats("debugInfo", JSON.stringify({currScript: "none", area: "out of game"}));

	while (true) {
		while (me.ingame) { // returns true before actually in game so we can't only use this check
			if (me.gameReady) { // returns false when switching acts so we can't use while
				if (!ingame) {
					lastGameStatus = "ingame";
					ingame = true;
					gameStart = getTickCount();
					DataFile.updateStats("runs", gameCount);
				}
				D2Bot.updateStatus("Game: " + me.gamename + timer(gameStart));
			}
			delay(1000);
		}
		locationAction();
		delay(1000);
	}
}

function joinCheck(leader) {
	D2Bot.requestGame(leader);
	delay(500);
	print(leader + " " + joinInfo.inGame + " " + lastGame.toSource() + " " + joinInfo.gameName);
	if (!joinInfo.inGame || (lastGame.length && lastGame.indexOf(joinInfo.gameName) === -1)) {
		D2Bot.printToConsole("Game is finished. Stopping join delay.");

		return true;
	}
	return false;
}

function locationAction() {
	if (me.ingame) {
		return;
	}

	var i, string, text, ScreenLocation = getLocation();

	MainSwitch:
	switch (ScreenLocation) {
		case 0: // Splash Screen
		break;
		case 8: // Main Screen
			ControlAction.click(6, 264, 433, 272, 35); //Other Multiplayer
			delay(500);
		break;
		case 12: // Character Select Screen
			try {
				login(me.profile);
			} catch (err) {
				print(err+" "+getLocation());
			}
		break;
		case 16: // Logging in Select
			delay(500);
		break;
		case 30: // Connecting
			ControlAction.click(6, 351, 337, 96, 32);
			delay(500);
		break;
		case 39: // Other Multiplayer Screen
			ControlAction.click(6, 264, 350, 272, 35); //TCP/IP Game
			delay(500);
		break;
		case 40: // TCP IP Screen
			// ControlAction.click(6, 265, 206, 272, 35); //Host Game
			ControlAction.click(6, 265, 264, 272, 35); //Join Game
			delay(500);
		break;
		case 41: // Join Game
			// ControlAction.click(6, 281, 337, 96, 32); //Cancel
			delay(500);
			D2Bot.updateStatus("Join Game");
			ControlAction.click(6, 421, 337, 96, 32); //Join
		break;
		default:
			if (ScreenLocation !== undefined) {
				D2Bot.printToConsole("Unhandled screen location " + ScreenLocation);
				delay(500);
				D2Bot.restart();
			}
		break;
	}
}