using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using hive;
using GameNetwork;
using GameCampaign;
using Game;
using GameUtility;
using hive.adkit.daro;

public class HomeManager : MonoBehaviour {

	public Toast toast;
	public Loading loading;

	public GameObject textVersion;

	public Image imageMainTitle;
	public Sprite spriteLogin;
	public Sprite spriteStart;

	public GameObject topButtonLayout;
	public Button buttonLeaderboards;
	public Button buttonAchievements;

	public GameObject panelBanner;
	public Button buttonStart;

	public Popup popup;
	public GameObject panelShop;
	public GameObject panelSettings;
	public GameObject panelCampaign;
	public GameObject panelPostsbox;
	public GameObject panelPermission;

	static bool isHome = true;
	static bool isGameSignIn = false;

	private int debugModeTimer = 0;
	private int debugModeClickCount = 0;

	// 버튼 중복 클릭 방지
	private bool _progressState;
	private bool inProgressing 
	{
		get {
			return _progressState;
		}
		set {
			_progressState = value;
			if (value) {
				// 다른 것이 처리중이다
				loading.show();
			} else {
				// 처리 중인 것이 없는 상태이다.
				loading.hide();
			}
		}
	}


	/* 게임 Sign-In 이 변경되면 로그인 UI 변경 */
	public bool IsGameSignIn {
		set {
			isGameSignIn = value;
			if (buttonStart != null) {
				buttonStart.GetComponent<Image>().sprite = isGameSignIn ? spriteStart : spriteLogin;
			}
			if (topButtonLayout != null) {
				topButtonLayout.SetActive (isGameSignIn);
			}
			if (panelBanner != null) {
				panelBanner.SetActive (isGameSignIn);
			}
			if (buttonLeaderboards != null) {
				buttonLeaderboards.gameObject.SetActive (isGameSignIn);
			}
			if (buttonAchievements != null) {
				buttonAchievements.gameObject.SetActive (isGameSignIn);
			}
		}
		get {
			return isGameSignIn;
		}
	}


	// Use this for initialization
	void Start () {
		Debug.Log ("HomeManager Start");

		IsGameSignIn = isGameSignIn;
//		buttonStart.GetComponent<Image>().sprite = isGameSignIn ? spriteStart : spriteLogin;

		textVersion.GetComponent<Text>().text = "Planet explore " + Application.version + "\nHIVE " + HIVEManager.shared.getHiveSdkVersion();
	}


	// Update is called once per frame
	void Update () {

#if UNITY_ANDROID
		if(isHome && Input.GetKeyDown(KeyCode.Escape))
		{
			HIVEManager.shared.showExit (onHIVEManagerShowExit);
		}
#endif

		debugModeTimer++;
		if (debugModeTimer > 240)
		{
			debugModeTimer = 0;
			debugModeClickCount = 0;
		}
	}


	public void onStartClick()
	{
		Debug.Log ("onStartClick");
		#if !UNITY_EDITOR
		if (inProgressing) {
			return;
		}
		#endif

		// if (HIVEManager.shared.isPermissionAgreed == false) {
		// 	inProgressing = true;
		// 	panelPermission.GetComponent<Permission>().getPermissionData(onHIVEPermission);
		// } else 
		if (HIVEManager.shared.isSetup == false) {
			hiveSetup();

		} else if (HIVEManager.shared.isSignIn == false) {
			Debug.Log ("HIVE SDK SIGN IN");
			inProgressing = true;
			HIVEManager.shared.signIn(onHIVEManagerSignIn);

		} else if (!IsGameSignIn) {
			Debug.Log ("GAME SIGN IN");
			GameSignIn();

		} else {
			Debug.Log ("LoadScene \"Main\"");

			HiveAdKitManager.shared.hideBanner();
			
			#if !UNITY_EDITOR
			GameConnect.shared.AccountGetItems((int errorCode, string message, List<Item> items, List<GameNetwork.Subscription> subscriptions) => {

				if (errorCode == 0) {
					if (items != null) {
						PlayerSettings.Instance ().Items = items;
					}
					SceneManager.LoadScene("Main", LoadSceneMode.Single);

				} else if (errorCode == 102) {
					popup.show(SBSLocalization.PopupKey.ACCOUNT_SESSION_INVALID, message, null, new string[] {"OK"}, (index) => {
						PlayerSettings.Instance ().reset ();
						IsGameSignIn = false;
					});

				} else {
					popup.show(SBSLocalization.PopupKey.SERVER_CONNECT_FAIL, message, null, new string[] {"OK"}, null);
				}
			});

			#else
			SceneManager.LoadScene("Main", LoadSceneMode.Single);
			
			#endif
		}
	}
	// HIVE SDK 초기화 요청
	public void hiveSetup () {

			inProgressing = true;
			#if UNITY_EDITOR
			HIVEManager.shared.isSetup = true;
			HIVEManager.shared.isSignIn = true;
			IsGameSignIn = true;

			popup.show("Sign Result", "UNITY_EDITOR test", "OK", null);
			inProgressing = false;
			#else
			Debug.Log ("HIVE SDK 초기화 요청");
			// 게임서버 설정
			HIVEManager.shared.setServerId("global");

			// HiveAdKit 초기화 이후 Setup 진행
			HiveAdKitManager.shared.AdKitInitialize(isSuccess =>
			{
				Debug.Log("onAdKitManagerInit " + isSuccess);

				// HIVE SDK 초기화 요청
				HIVEManager.shared.setup(onHIVEManagerSetup);
			});
			#endif
	}

	public void onLeaderboardsClick()
	{
		Debug.Log ("onLeaderboardsClick");

		HIVEManager.shared.showLeaderboard(onHIVEManagerShowLeaderboard);
	}

	public void onAchievemnetsClick()
	{
		Debug.Log ("onAchievemnetsClick");

		HIVEManager.shared.showAchievements(onHIVEManagerShowAchievements);
	}

	public void onSettingsClick(bool isEnter)
	{
		Debug.Log ("onSettingsClick");
		isHome = !isEnter;
		panelSettings.SetActive (isEnter);

		if (isEnter) {
			panelSettings.GetComponent<Settings> ().open ();
		}
	}

	public void onEventClick()
	{
		Debug.Log ("onEventClick");

		HIVEManager.shared.promotionShowNews();
	}

	public void onPostboxClick(bool isEnter)
	{
		Debug.Log("onPostboxClick");
		isHome = !isEnter;

		if (isEnter) {
			panelPostsbox.SetActive (isEnter);
			panelPostsbox.GetComponent<PostManager>().Show();
		} else {
			panelPostsbox.GetComponent<PostManager>().Dismiss();
			panelPostsbox.SetActive (isEnter);
		}
	}

	/*
	* Promotion 의 UA (User Acqusition) 기능.
	* API 로는 친구 초대 기능인 Promotion.getAppInvitationData()
	*/
	public void onCampaignClick(bool isEnter)
	{
		Debug.Log ("onCampaignClick");
		isHome = !isEnter;
		CampaignManager manager = panelCampaign.GetComponent<CampaignManager>();

		if (isEnter) {
			if (manager.IsShow) {
				Debug.Log("Already show 'Campaign Panel'.");
			}
			else {
				manager.Show();
			}
			
		} else {
			manager.Dismiss();
		}
	}


	public void onShopClick(bool isEnter)
	{
		Debug.Log ("onShopClick");
		isHome = !isEnter;
		panelShop.SetActive (isEnter);
		if (isEnter) {
			panelShop.GetComponent<Shop> ().open ();
		}
	}

	public void GameSignIn()
	{
		inProgressing = true;
		GameConnect.shared.SignIn(onGameConnectSignIn);
	}

	//====================================
	//	HIVEManager 콜백 핸들러
	//====================================

	void onHIVEPermission(bool finishToShow)
	{

		Debug.Log("onHIVEPermission");
		if (finishToShow) {
			this.hiveSetup ();
		} else {
			inProgressing = false;
		}
	}
	void onHIVEManagerSetup(bool isSuccess, string message)
	{
		Debug.Log("onHIVEManagerSetup");

		if (isSuccess == true) {
			HIVEManager.shared.checkMaintenance (onHIVEManagerCheckMaintenance);
		} else {
			inProgressing = false;		
			popup.show(SBSLocalization.PopupKey.HIVE_SETUP_FAIL, message, null, new string[] {"OK"}, null);
		}
	}

	public void onHIVEManagerSignIn(bool isSuccess, string message)
	{
		Debug.Log("onHIVEManagerSignIn");

		if (isSuccess == true) {
			GameSignIn();
			// HiveAdKitManager.shared.ReadyAds(); // 로그인 성공 시 AdKit 광고 레디
			HiveAdKitManager.shared.loadBanner();
			HIVEManager.shared.promotionShowBanner(); // 로그인 성공시 promotionShowBanner 진행
		} else {
			inProgressing = false;
			popup.show(SBSLocalization.PopupKey.HIVE_SIGNIN_FAIL, message, null, new string[] {"OK"}, null);
		}
	}

	public void onHIVEManagerSignOut(bool isSuccess, string message)
	{
		Debug.Log ("onHIVEManagerSignOut");

		/* 게임과 HIVE SDK 의 Sign-In Flag 값도 초기화 */
		PlayerSettings.Instance ().reset ();
		IsGameSignIn = false;
	}

	public void onHIVEManagerCheckMaintenance(bool isSuccess, string message)
	{
		Debug.Log ("onHIVEManagerCheckMaintenance");
		if (isSuccess) {
			HIVEManager.shared.signIn(onHIVEManagerSignIn);

		} else {
			popup.show(SBSLocalization.PopupKey.CHECKMAINTENANCE_FAILED, message, null, new string[] { "Retry" }, (int clickBtnIndex) => {
				HIVEManager.shared.checkMaintenance(onHIVEManagerCheckMaintenance);
			});
		}
	}

	public void onHIVEManagerShowAchievements(bool isSuccess, string message, bool moveToTitle)
	{
		Debug.Log ("onHIVEManagerShowAchievements - " + message);

		if (!isSuccess) {
			popup.show(SBSLocalization.PopupKey.UNKNOWN_ERROR, message, null, new string[] {"OK"}, null);
		}

		if (moveToTitle == true) {
			int scene = SceneManager.GetActiveScene().buildIndex;
			SceneManager.LoadScene(scene, LoadSceneMode.Single);
		}
	}

	public void onHIVEManagerShowLeaderboard(bool isSuccess, string message, bool moveToTitle)
	{
		Debug.Log ("onHIVEManagerShowLeaderboard - " + message);

		if (!isSuccess) {
			popup.show(SBSLocalization.PopupKey.UNKNOWN_ERROR, message, null, new string[] {"OK"}, null);
		}

		if (moveToTitle == true) {
			int scene = SceneManager.GetActiveScene().buildIndex;
			SceneManager.LoadScene(scene, LoadSceneMode.Single);
		}
	}

	public void onHIVEManagerShowExit(bool isSuccess, string message)
	{
		Debug.Log ("onHIVEManagerShowExit - " + isSuccess + " message: " + message);

		if (isSuccess == true) {
#if UNITY_EDITOR
			UnityEditor.EditorApplication.isPlaying = false;
#else
			Application.Quit();
#endif
		}
	}

	//====================================
	//	GameConnect 콜백 핸들러
	//====================================
	public void onGameConnectSignIn(bool success, string message) 
	{
		IsGameSignIn = success;

		if (success == true) {
			inProgressing = false;
			HIVEManager.shared.didLogin ();
		} else {
			inProgressing = false;
			if (string.IsNullOrEmpty(message)) {
				popup.show(SBSLocalization.PopupKey.SERVER_CONNECT_FAIL, message, null, new string[] {"OK"}, null);
			} else {
				popup.show(SBSLocalization.PopupKey.HIVE_SIGNIN_FAIL, message, null, new string[] {"OK"}, null);
			}
		}
	}


	public void onVersionClick()
	{
		string buildDate = "2026.01.27_1";
		debugModeClickCount++;
		if (debugModeClickCount == 5)
		{
			#if UNITY_EDITOR
			Debug.Log ("onVersionClick - Logger Enabled. " + buildDate);
			#else
			if (!Configuration.getUseLog())
			{
				toast.show ("Logger Enabled. - " + buildDate);
				Configuration.setUseLog(true);
				Configuration.setGameLanguage("en");
			}
			HIVEAdKit.SetLogEnable(true);
			#endif
		}

		if (debugModeClickCount == 10)
		{
			#if UNITY_EDITOR
			Debug.Log ("onVersionClick - Test Enabled. " + buildDate);
			#else
			if (!(HIVEManager.isTestZone()))
			{
				toast.show ("Test Enabled. - " + buildDate);
				HIVEManager.setTestZone();
				// Test 서버 설정으로 file system 기준 변경
				Configuration.setGameLanguage("en");
			}
			#endif
		}

	}
}
