var Ranking = {

	preload: function() {
		game.load.image('icon_fullscreen', '../../../resources/image/icon/fullscreen_white.png');
		game.load.image('bg_white', '../../../resources/image/ui/white_rect.png');
	},

	create: function() {
		this.dbConnectManager = new DBConnectManager();

		this.dbService = new DBService();
		this.dbService.setMaestroID(sessionStorageManager.getMaestroID());
		this.dbService.setPlayerID(sessionStorageManager.getPlayerID());

		this.jsonData = null;
		this.timeType = Ranking.MODE_HOUR;
		this.refreshTimeSec = Ranking.REFRESH_TIME_SEC;

		this.showingPageIndex = 0;
		this.recordArray = [];

		this.dateTime = null;
		this.date = "";
		this.time = "";
		this.getDateTimeNow();

		// bg
		this.game.stage.backgroundColor = '#4d4d4d';

		var posY = 100;
		this.bgTimeline = game.add.sprite(0, 60, "bg_white");
		this.bgTimeline.width = GAME_SCREEN_SIZE.x;
		this.bgTimeline.height = 80;
		this.setBgColor(this.timeType);


		// keyboard shortcut
		this.keyboardShortcut = new KeyboardShortcut();
		this.keyboardShortcut.addCallback(
			Phaser.KeyCode.ESC,	// keyCode
			null,	// keyDownHandler
			(function() { this.back(); }).bind(this),	// keyUpHandler
			"ranking"	// callerClassName
		);

		// top ui
		var screenTopUI = new ScreenTopUI();
		screenTopUI.makeBackButton( (function() { this.back(); }).bind(this) );
		screenTopUI.makeFullScreenButton();


		var resultTextStyle = textStyleBasic;
		resultTextStyle.font = "bold 42px Arial";

		this.textTitle = game.add.text(
			GAME_SCREEN_SIZE.x / 2, 32,
			sessionStorageManager.getPlayingAppKoreanName() + " - 수업시간 순위",
			resultTextStyle
		).setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2);
		this.textTitle.anchor.set(0.5);
		this.textTitle.addColor("#ff6666", 0);


		// date time
		this.textDateTime = game.add.text(GAME_SCREEN_SIZE.x / 2, 104, "", resultTextStyle);
		this.textDateTime.fontSize = 28;
		this.textDateTime.fontWeight = "normal";
		this.textDateTime.stroke = "#333333";
		this.textDateTime.strokeThickness = 3;
		//.setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2);
		this.textDateTime.anchor.set(0.5);
		// this.textDateTime.addColor("#ff6666", 0);
		this.printDateTime(this.dateTime);


		// ranking text
		var rankingTextOffsetY = 190;
		this.rankingTexts = new Array();
		for(var i = 0; i < Ranking.RANK_COUNT; i++) {
			var posX = ( (i < 10) ? 120 : 80 + (GAME_SCREEN_SIZE.x / 2) );
			var posY = rankingTextOffsetY + (i % 10) * 40;
			this.rankingTexts[i] = new RankingText(
				RankingText.PLACE_FOR_RANKING,
				posX, posY,
				sessionStorageManager.getPlayingAppID()
			);
		}


		var buttonOffsetX = 320;
		var buttonPositionY = 100;
		var dateTimeButtonWidth = 40;
		this.buttonPrevDate = this.makeArrowButton(
			buttonOffsetX, buttonPositionY,
			dateTimeButtonWidth, dateTimeButtonWidth,
			"<",
			(function() { this.decreaseDateTime(); }).bind(this)
		);
		// this.buttonPrevDate.inputEnabled = false;
		this.buttonNextDate = this.makeArrowButton(
			GAME_SCREEN_SIZE.x - buttonOffsetX, buttonPositionY,
			dateTimeButtonWidth, dateTimeButtonWidth,
			">",
			(function() { this.increaseDateTime(); }).bind(this)
		);
		// this.buttonNextDate.inputEnabled = false;

		var buttonTestDate = null;
		if(runMode == MODE_DEBUG) {
			buttonTestDate = this.makeArrowButton(
				30, buttonPositionY,
				50, 50,
				"@",
				(function() {
					this.date = "2018-08-23";
					this.time = "15:53:00";
					this.dateTime = new Date(this.date + "T" + this.time);
					this.getRecordToRankingServer();
				}).bind(this)
			);
		}


		buttonOffsetX = 30;
		buttonPositionY = 370;
		this.buttonPrevRanking = this.makeArrowButton(
			buttonOffsetX, buttonPositionY,
			50, 400,
			"<",
			(function() { this.onClickPrevRanking(); }).bind(this)
		);
		// this.buttonPrevRanking.setInputEnabled(false);
		this.buttonNextRanking = this.makeArrowButton(
			GAME_SCREEN_SIZE.x - buttonOffsetX, buttonPositionY,
			50, 400,
			">",
			(function() { this.onClickNextRanking() }).bind(this)
		);
		// this.buttonNextRanking.setInputEnabled(false);


		buttonPositionY = 650;
		var buttonHour = this.makeTextButton(
			game.world.centerX - 220, buttonPositionY,
			"수업시간 순위",
			(function() { this.onClickRankingHour(); }).bind(this)
		);
		// buttonHour.setInputEnabled(false);
		var buttonDay = this.makeTextButton(
			game.world.centerX, buttonPositionY,
			"오늘의 순위",
			(function() { this.onClickRankingDay(); }).bind(this)
		);
		// buttonDay.setInputEnabled(false);
		var buttonMonth = this.makeTextButton(
			game.world.centerX + 220, buttonPositionY,
			"이달의 순위",
			(function() { this.onClickRankingMonth(); }).bind(this)
		);
		// buttonMonth.setInputEnabled(false);


		// bottom ui
		this.screenBottomUI = new ScreenBottomUI();
		// ScreenBottomUI.printLeftText("게임 진행 정보");
		// var playingAppName = appInfoManager.getAppNameKorean(sessionStorageManager.getPlayingAppName());
		// ScreenBottomUI.printCenterText(playingAppName);
		// this.screenBottomUI.printCenterText("수업시간 순위");
		this.screenBottomUI.printRightText(sessionStorageManager.getPlayerName());

		this.getRecordToRankingServer();
		game.time.events.loop(Phaser.Timer.SECOND * this.refreshTimeSec, this.getRecordToRankingServer, this);
	},


	back: function() {
		location.href = '../../web/client/start.html';
	},

	makeArrowButton: function(x, y, width, height, buttonText, eventListener) {
		var setting = new RoundRectButtonSetting(x, y, width, height);
		setting.fontStyle.fontWeight = "bold";
		setting.strokeColors = {
			out: 0x444444,	// 0xdddddd,
			over: 0x333333,	// 0xcccccc,
			down: 0x222222,	// 0xbbbbbb,
			disabled: 0x333333
		};
		setting.buttonColors = {
			out: 0x666666,	// 0xffffff,
			over: 0x444444,	// 0xdddddd,
			down: 0x333333,	// 0xcccccc,
			disabled: 0x333333
		};
		setting.textColors = {
			out: "#fff",	// "#000",
			over: "#000",
			down: "#000",
			disabled: "#999"
		};

		return new RoundRectButton(setting, RoundRectButton.NONE_ICON, buttonText, eventListener);
	},

	makeTextButton: function(x, y, buttonText, eventListener) {
		var setting = new RoundRectButtonSetting(x, y, 200, 100);
		setting.fontStyle.fontWeight = "bold";
		switch(buttonText) {
			case "수업시간 순위":
			setting.strokeColors = {
				out: 0xddcccc,
				over: 0xccaaaa,
				down: 0xbb9999,
				disabled: 0x333333
			};
			setting.buttonColors = {
				out: 0xffeeee,
				over: 0xddcccc,
				down: 0xccaaaa,
				disabled: 0x333333
			};
			setting.textColors = {
				out: "#f00",
				over: "#f00",
				down: "#f00",
				disabled: "#999"
			};
			break;

			case "오늘의 순위":
			setting.strokeColors = {
				out: 0xccccdd,
				over: 0xaaaacc,
				down: 0x9999bb,
				disabled: 0x333333
			};
			setting.buttonColors = {
				out: 0xeeeeff,
				over: 0xccccdd,
				down: 0xaaaacc,
				disabled: 0x333333
			};
			setting.textColors = {
				out: "#00f",
				over: "#00f",
				down: "#00f",
				disabled: "#999"
			};
			break;

			case "이달의 순위":
			setting.strokeColors = {
				out: 0xccddcc,
				over: 0xaaccaa,
				down: 0x99bb99,
				disabled: 0x333333
			};
			setting.buttonColors = {
				out: 0xeeffee,
				over: 0xccddcc,
				down: 0xaaccaa,
				disabled: 0x333333
			};
			setting.textColors = {
				out: "#0f0",
				over: "#0f0",
				down: "#0f0",
				disabled: "#999"
			};
			break;

		}

		return new RoundRectButton(setting, RoundRectButton.NONE_ICON, buttonText, eventListener);
	},

	getDateTimeType: function() {
		var dateTimeType = -1;
		switch(this.timeType) {
			case Ranking.MODE_HOUR:
			dateTimeType = DBConnectManager.TYPE_MY_RANKING_HOUR;
			break;

			case Ranking.MODE_DAY:
			dateTimeType = DBConnectManager.TYPE_MY_RANKING_DAY;
			break;

			case Ranking.MODE_MONTH:
			dateTimeType = DBConnectManager.TYPE_MY_RANKING_MONTH;
			break;
		}

		return dateTimeType;
	},

	getRndInteger: function(min, max) {
		return Math.floor(Math.random() * (max - min + 1) ) + min;
	},

	getSampleRankingRecord: function() {
		var rankingRecordManager = new RankingRecordManager();

		var playerNameList = [
			"김가람", "강가온", "고길", "한나라", "강나래",
			"오나예", "박노아", "부노을", "한다은", "최두루",
			"신두나", "최해솔", "김모든", "설보라", "민모든",
			"이보람", "이빛길", "정새론", "한새얀", "채세련",
			"태슬예", "진승아", "강시원", "김아롱", "박알찬",
			"김다은", "황세련", "강원", "지소은", "남궁민"
		];
		var shuffleList = Phaser.ArrayUtils.shuffle(playerNameList);
		for(var i = 0; i < 30; i++) {
			var record = new RankingRecord(
				i + 1,	// rank
				i + 1,	// playerID
				shuffleList[i],	// playerName
				this.getRndInteger(1000 - (i + 1) * 20, 1000 - (i + 1) * 10)	// record
			);
			rankingRecordManager.push(record);
		}

		return rankingRecordManager;
	},

	getRecordToRankingServer: function() {
		this.recordArray == [];

		if(isExperiencePlayerAccount() || isExperienceMaestroAccount()) {
			this.showRanking(this.getSampleRankingRecord());
			return;
		}

		if(isTypingExamApp()) {
			this.dbService.requestTypingExamRanking(
				this.getDateTimeType(),
				sessionStorageManager.getWritingID(),
				this.date,
				this.time,

				(function(type, rankingRecordManager) {
					this.showRanking(rankingRecordManager);
				}).bind(this),

				(function(jsonData) {
					console.log(jsonData);
				}).bind(this)
			);
		} else {
			this.dbConnectManager.requestRanking(
				this.getDateTimeType(),
				sessionStorageManager.getMaestroID(),
				this.date,
				this.time,

				(function(type, rankingRecordManager) {
					this.showRanking(rankingRecordManager);
				}).bind(this),

				(function(jsonData) {
					console.log(jsonData);
				}).bind(this)
			);
		}
	},

	onClickRankingHour: function() {
		this.timeType = Ranking.MODE_HOUR;
		this.textTitle.text = sessionStorageManager.getPlayingAppKoreanName() + " - 수업시간 순위";
		this.textTitle.addColor("#ff6666", 0);

		this.printDateTime(this.dateTime);

		this.getRecordToRankingServer();
		this.setFirstPageIndex();
		this.setBgColor(this.timeType);
	},

	onClickRankingDay: function() {
		this.timeType = Ranking.MODE_DAY;
		this.textTitle.text = sessionStorageManager.getPlayingAppKoreanName() + " - 오늘의 순위";
		this.textTitle.addColor("#9999ff", 0);

		this.printDateTime(this.dateTime);

		this.getRecordToRankingServer();
		this.setFirstPageIndex();
		this.setBgColor(this.timeType);
	},

	onClickRankingMonth: function() {
		this.timeType = Ranking.MODE_MONTH;
		this.textTitle.text = sessionStorageManager.getPlayingAppKoreanName() + " - 이달의 순위";
		this.textTitle.addColor("#99ff99", 0);

		this.printDateTime(this.dateTime);

		this.getRecordToRankingServer();
		this.setFirstPageIndex();
		this.setBgColor(this.timeType);
	},

	showRanking: function(rankingRecordManager) {
		this.recordArray = [];

		if(rankingRecordManager.getCount() == 0) {
			this.setFirstPageIndex();
			this.printRanking();
			return;
		}

		var rankingListCount = rankingRecordManager.getCount();
		for(var i = 0; i < rankingListCount; i++) {
			var record = [];
			// record[0] = jsonRankingList[i]['UserID'];
			record[0] = rankingRecordManager.getPlayerIDAt(i);	// playerID
			// record[1] = i + 1;	// ranking
			record[1] = rankingRecordManager.getRankAt(i);;	// ranking
			record[2] = rankingRecordManager.getPlayerNameAt(i);
			record[3] = rankingRecordManager.getBestRecordAt(i);
			// console.log("record : " + record[0] + ", "  + record[1] + ", "  + record[2] + ", "  + record[3]);

			this.recordArray.push(record);
		}

		this.printDateTime(this.dateTime);
		this.printRanking();
	},

	emptyRanking: function() {
		for(var i = 0; i < Ranking.RANK_COUNT; i++) {
			this.rankingTexts[i].reset();
		}
	},

	printRanking: function() {
		this.emptyRanking();
		this.updateRankingNavigationButtons();

		if(this.recordArray.length == 0)
			return;

		// timezone changed (ex: 2pm -> 3pm)
		if(this.showingPageIndex * 20 > this.recordArray.length)
			this.setFirstPageIndex();

		// print
		for(var i = 0; i < Ranking.RANK_COUNT; i++) {
			var index = this.showingPageIndex * 20 + i;
			var record = this.recordArray[index];
			if(typeof record == "undefined")
				break;
			this.rankingTexts[i].setContents(record[0], record[1], record[2], record[3]);
		}

		this.updateRankingNavigationButtons();
	},

	updateRankingNavigationButtons: function() {
		if(this.recordArray.length == 0) {
			this.buttonPrevRanking.text.text = "X";
			this.buttonNextRanking.text.text = "X";
			return;
		}
		if(this.showingPageIndex > 0)
			this.buttonPrevRanking.text.text = "<";
		else
			this.buttonPrevRanking.text.text = "X";

		if((this.showingPageIndex + 1) * 20 < this.recordArray.length)
			this.buttonNextRanking.text.text = ">";
		else
			this.buttonNextRanking.text.text = "X";
	},

	getDateTimeNow: function() {
		var now = new Date();
		var hourTimeText = DateUtil.getYYYYMMDD(now) + "T" + DateUtil.getFullHours(now) + ":00:00";
		this.dateTime = new Date(hourTimeText);
		this.date = DateUtil.getYYYYMMDD(this.dateTime);
		this.time = DateUtil.getHHMMSS(this.dateTime);
	},

	setDateTime: function(dateTime) {
		this.date = DateUtil.getYYYYMMDD(dateTime);
		this.time = DateUtil.getHHMMSS(dateTime);
	},

	increaseDateTime: function() {
		switch(this.timeType) {
			case Ranking.MODE_HOUR:
			this.dateTime.setHours(this.dateTime.getHours() + 1);
			break;

			case Ranking.MODE_DAY:
			this.dateTime.setDate(this.dateTime.getDate() + 1);
			break;

			case Ranking.MODE_MONTH:
			this.dateTime.setMonth(this.dateTime.getMonth() + 1);
			break;
		}
		this.setDateTime(this.dateTime);

		this.printDateTime(this.dateTime);
		this.getRecordToRankingServer();
	},

	decreaseDateTime: function() {
		switch(this.timeType) {
			case Ranking.MODE_HOUR:
			this.dateTime.setHours(this.dateTime.getHours() - 1);
			break;

			case Ranking.MODE_DAY:
			this.dateTime.setDate(this.dateTime.getDate() - 1);
			break;

			case Ranking.MODE_MONTH:
			this.dateTime.setMonth(this.dateTime.getMonth() - 1);
			break;
		}
		this.setDateTime(this.dateTime);

		this.printDateTime(this.dateTime);
		this.getRecordToRankingServer();
	},

	getDatetimeHour: function() {
		return this.dateTime.getHours();
	},

	getDatetimeHourWith2Digits: function() {
		return ("0" + this.dateTime.getHours()).slice(-2);
	},

	getYYYYMMDDHHText: function(dateTime) {
		return DateUtil.getFullYear(dateTime) + "년 "
			+ DateUtil.getFullMonth(dateTime) + "월 "
			+ DateUtil.getFullDate(dateTime) + "일, "
			+ DateUtil.getFullHours(dateTime) + "시";
	},

	getYYYYMMDDText: function(dateTime) {
		return DateUtil.getFullYear(dateTime) + "년 "
			+ DateUtil.getFullMonth(dateTime) + "월 "
			+ DateUtil.getFullDate(dateTime) + "일";
	},

	getYYYYMMText: function(dateTime) {
		return DateUtil.getFullYear(dateTime) + "년 "
			+ DateUtil.getFullMonth(dateTime) + "월 ";
	},

	printDateTime: function(dateTime) {
		// console.log(this.timeType);
		// console.log((this.dateTime);

		switch(this.timeType) {
			case Ranking.MODE_HOUR:
			this.textDateTime.text = this.getYYYYMMDDHHText(dateTime);
			break;

			case Ranking.MODE_DAY:
			this.textDateTime.text = this.getYYYYMMDDText(dateTime);
			break;

			case Ranking.MODE_MONTH:
			this.textDateTime.text = this.getYYYYMMText(dateTime);
			break;
		}
	},

	onClickPrevRanking: function() {
		if(this.recordArray.length == 0)
			return;

		this.showingPageIndex--;
		if(this.showingPageIndex < 0)
			this.showingPageIndex = 0;

		this.printRanking();
	},

	onClickNextRanking: function() {
		if(this.recordArray.length == 0)
			return;

		if((this.showingPageIndex + 1) * 20 < this.recordArray.length)
			this.showingPageIndex++;
		this.printRanking();
	},

	setFirstPageIndex: function() {
		this.showingPageIndex = 0;
	},

	setBgColor: function(timeType) {
		switch(timeType) {
			case Ranking.MODE_HOUR:
			this.bgTimeline.tint = 0x5f4d4d;
			break;

			case Ranking.MODE_DAY:
			this.bgTimeline.tint = 0x4d4d5f;
			break;

			case Ranking.MODE_MONTH:
			this.bgTimeline.tint = 0x4d5f4d;
			break;
		}
	},
}

Ranking.MODE_HOUR	= "mode_hour";
Ranking.MODE_DAY	= "mode_day";
Ranking.MODE_MONTH	= "mode_month";

Ranking.REFRESH_TIME_SEC	= 5;

Ranking.RANK_COUNT	= 20;