using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using hive;
using GameNetwork;
using Game;


public class Settings : MonoBehaviour  {

	public HomeManager homeManager;

	public Notification notification;

	public Popup popup;
	public Loading loading;

	public Button buttonMyProfile;

	public Button buttonNotification;

	public Text textCSCode;
	public Text textGameID;
	public Text textLevel;
	public Text textGameLanguage;


	public Button buttonGoogle;
	public Sprite spritePGOn;
	public Sprite spritePGOff;
	public Sprite spritePGIng;

	public Button buttonGooglePlayGames;
	public Sprite spritePGSOn;
	public Sprite spritePGSOff;
	public Sprite spritePGSIng;

	public Button buttonFacebook;
	public Sprite spriteFBOn;
	public Sprite spriteFBOff;
	public Sprite spriteFBIng;

	public Button buttonHIVE;
	public Sprite spriteHIVEOn;
	public Sprite spriteHIVEOff;
	public Sprite spriteHIVEIng;

	public Button buttonGameCenter;
	public Sprite spriteGameCenterOn;
	public Sprite spriteGameCenterOff;
	public Sprite spriteGameCenterIng;

	public Button buttonAppleSignIn;
	public Sprite spriteAppleSignInOn;
	public Sprite spriteAppleSignInOff;
	public Sprite spriteAppleSignInIng;

	public Button buttonLine;
	public Sprite spriteLineOn;
	public Sprite spriteLineOff;
	public Sprite spriteLineIng;


	bool enableGameCenter = false;
	bool enableGoogle = false;
	bool enableGooglePlayGames = false;
	bool enableFacebook = false;
	bool enableHive = false;
	bool enableAppleSignIn = false;
	bool enableLine = false;

	public Button buttonLogOut;
	public Sprite spriteLogOutActive;
	public Sprite spriteLogOutInActive;

	public Text idpSyncNoticeText;

	private int crashModeClickCount = 0;

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


	public void open ()
	{
		Debug.Log ("Settings open");

		uiInitialize();
	}

	void Update () {
		if(Input.GetKeyDown(KeyCode.Escape))
		{
			if (popup.gameObject.activeSelf) {
				popup.dismiss();
			} else if (notification.gameObject.activeSelf) {
				notification.gameObject.SetActive(false);
			} else {
				homeManager.onSettingsClick(false);
			}
		}
	}

	private void uiInitialize() 
	{
		setProviderButton();
		setLogoutButton();
		GameConnect.shared.AccountGetItems((int errorCode, string message, List<Item> items, List<GameNetwork.Subscription> subscriptions) => {
			if (errorCode == 102) {
				popup.show(SBSLocalization.PopupKey.ACCOUNT_SESSION_INVALID, message, null, new string[] {"OK"}, (index) => {
					PlayerSettings.Instance ().reset ();
					homeManager.IsGameSignIn = false;
					homeManager.onSettingsClick(false);
				});
			}
		});
	}

	/* Player 의 연동된 IDP 에 따라 버튼을 표시 */
	void setProviderButton()
	{
		StartCoroutine(downloadTexture( AuthV4.getPlayerInfo ().playerImageUrl ));

		textCSCode.text = "" + AuthV4.getPlayerInfo ().playerId;
		textGameID.text = AuthV4.getPlayerInfo().playerName;
		// Level
		HIVEManager.shared.dataStoreGet("PlayerLevel", (bool isSuccess, string data) =>
        {
            if (isSuccess) {
				if (data.Equals("0")) {
                	textLevel.text = "1";
                } else {
					textLevel.text = data;
                }
            }
        });
		textGameLanguage.text = "en";

		enableGameCenter = false;
		enableGoogle = false;
		enableGooglePlayGames = false;
		enableFacebook = false;
		enableHive = false;
		enableAppleSignIn = false;
		enableLine = false;

#if !UNITY_EDITOR

		GameObject[] idpButtons = GameObject.FindGameObjectsWithTag("IDPButton");
		foreach (GameObject button in idpButtons) {
			button.SetActive(false);
		}

		List<AuthV4.ProviderType> idpList = AuthV4.Helper.getIDPList ();

		foreach (AuthV4.ProviderType providerType in idpList) {
			switch (providerType) {

			case AuthV4.ProviderType.GOOGLE:
				buttonGoogle.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.GOOGLE_PLAY_GAMES:
				buttonGooglePlayGames.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.APPLE:
				buttonGameCenter.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.FACEBOOK:
				buttonFacebook.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.HIVE:
				buttonHIVE.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.SIGNIN_APPLE:
				buttonAppleSignIn.gameObject.SetActive(true);
				break;

			case AuthV4.ProviderType.LINE:
				buttonLine.gameObject.SetActive(true);
				break;

			default:
				// nothing to do
				break;
			}
		}



		Dictionary<AuthV4.ProviderType, AuthV4.ProviderInfo> providerInfo = AuthV4.getPlayerInfo().providerInfoData;

		foreach (AuthV4.ProviderType type in providerInfo.Keys) {
			switch (type) {

			case AuthV4.ProviderType.GOOGLE:
				enableGoogle = true;
				break;

			case AuthV4.ProviderType.GOOGLE_PLAY_GAMES:
				enableGooglePlayGames = true;
				break;

			case AuthV4.ProviderType.APPLE:
				enableGameCenter = true;
				break;

			case AuthV4.ProviderType.FACEBOOK:
				enableFacebook = true;
				break;

			case AuthV4.ProviderType.HIVE:
				enableHive = true;
				break;

			case AuthV4.ProviderType.SIGNIN_APPLE:
				enableAppleSignIn = true;
				break;

			case AuthV4.ProviderType.LINE:
				enableLine = true;
				break;

			default:
				// nothing to do
				break;
			}
		}
#endif


		buttonGoogle.GetComponent<Image>().sprite = enableGoogle ? spritePGOn : spritePGOff;
		buttonGooglePlayGames.GetComponent<Image>().sprite = enableGooglePlayGames ? spritePGSOn : spritePGSOff;
		buttonGameCenter.GetComponent<Image>().sprite = enableGameCenter ? spriteGameCenterOn : spriteGameCenterOff;
		buttonFacebook.GetComponent<Image>().sprite = enableFacebook ? spriteFBOn : spriteFBOff;
		buttonHIVE.GetComponent<Image>().sprite = enableHive ? spriteHIVEOn : spriteHIVEOff;
		buttonAppleSignIn.GetComponent<Image>().sprite = enableAppleSignIn ? spriteAppleSignInOn : spriteAppleSignInOff;
		buttonLine.GetComponent<Image>().sprite = enableLine ? spriteLineOn : spriteLineOff;
		

		bool ageGateU13 = HIVEManager.shared.getAgeGateU13 ();

		buttonNotification.gameObject.SetActive(!ageGateU13);
		buttonGoogle.enabled = !ageGateU13;
		buttonGooglePlayGames.enabled = !ageGateU13;
		buttonFacebook.enabled = !ageGateU13;
		buttonHIVE.enabled = !ageGateU13;
		buttonGameCenter.enabled = !ageGateU13;
		buttonAppleSignIn.enabled = !ageGateU13;
		buttonLine.enabled = !ageGateU13;
	}


	void setLogoutButton() {
		// 게스트 로그인 상태인 경우 로그아웃 버튼을 비활성화 한다.
		Dictionary<AuthV4.ProviderType, AuthV4.ProviderInfo> providerInfo = AuthV4.getPlayerInfo().providerInfoData;

		if(providerInfo.Count == 0) {
			buttonLogOut.image.overrideSprite = spriteLogOutInActive;
			buttonLogOut.interactable = false;
			buttonLogOut.gameObject.SetActive(false);
			idpSyncNoticeText.gameObject.SetActive(true);
			// buttonLogOut.setAc
		} else {
			buttonLogOut.image.overrideSprite = spriteLogOutActive;
			buttonLogOut.interactable = true;
			buttonLogOut.gameObject.SetActive(true);
			idpSyncNoticeText.gameObject.SetActive(false);
		}
	}


	IEnumerator downloadTexture(string url) {

		Debug.Log ("downloadTexture : " + url.Replace(@"\", ""));

		if (url != null) {
			// Start a download of the given URL
			WWW www = new WWW(url.Replace(@"\", ""));
			// wait until the download is done
			yield return www;
			// Create a texture in DXT1 format
			// Texture2D texture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.DXT1, false);

			// assign the downloaded image to sprite
			// www.LoadImageIntoTexture(texture);

			// buttonMyProfile.GetComponent<RawImage> ().texture = www.texture;

			Rect rec = new Rect(0, 0, www.texture.width, www.texture.height);
			Sprite spriteToUse = Sprite.Create(www.texture, rec, new Vector2(0.5f, 0.5f), 100);
			buttonMyProfile.GetComponent<Image>().sprite = spriteToUse;

			www.Dispose();
			www = null;
		}
	}


	void onHIVEManagerShowProfile(bool success, string message)
	{
		Debug.Log ("onHIVEManagerShowProfile : " + message);

		// showProfile() 콜백 핸들러. HIVE 연동 유저의 경우 프로필 이미지를 바꾸거나 연동을
		// 해제 할 수 있기 때문에, 프로필 웹뷰가 닫히면 데이터를 갱신해준다.
		uiInitialize();
	}


	public void onMyProfileClick()
	{
		Debug.Log ("onMyProfileClick");
		
		#if UNITY_EDITOR
		onHIVEManagerShowProfile(true, "Success");
		#else
		HIVEManager.shared.showProfile(onHIVEManagerShowProfile);
		#endif // #if UNITY_EDITOR
	}
	/* MyProfile end */


	/* Notification start */
	public void onNotificationClick()
	{
		Debug.Log ("onNotificationClick");

		notification.gameObject.SetActive(true);
	}
	/* Notification end */


	/*  */
	public void onGameResetClick() 
	{
		Debug.Log ("onGameResetClick");
		// 과거 '게임 데이터 초기화' 로 동작시 코드
		popup.show(SBSLocalization.PopupKey.RESET_ACCOUNT, null, null, new string [] { "Cancel" ,"Reset" }, (int clickBtnIndex) =>{
			if (clickBtnIndex == 1 ) {
				GameConnect.shared.ResetAccount(onGameConnectResetAccount);
			} 
		});		
	}


	void onGameConnectResetAccount(bool success)
	{
		// TODO: Daun - 게임 초기화 기능 구현
		PlayerSettings.Instance ().reset ();
		homeManager.IsGameSignIn = false;
		homeManager.onSettingsClick (false);

		if (success) {

			Debug.Log ("LoadScene \"Home\"");

			SceneManager.LoadScene("Home", LoadSceneMode.Single);
		}
	}


	public void onGameDeleteAccountClick()
	{
		Debug.Log ("onGameDeleteAccountClick");
		// 계정 삭제 GCPPMM-1403
		#if UNITY_ANDROID
		popup.show(SBSLocalization.PopupKey.DELETE_ACCOUNT_ANDROID, null, null, new string [] { "Cancel" ,"Delete" }, (int clickBtnIndex) =>{
			if (clickBtnIndex == 1 ) {
				inProgressing = true;
				GameConnect.shared.DeleteAccount(onGameConnectDeleteAccount);
			} 
		});
		#elif UNITY_IOS
		popup.show(SBSLocalization.PopupKey.DELETE_ACCOUNT_IOS, null, null, new string [] { "Cancel" ,"Delete" }, (int clickBtnIndex) =>{
			if (clickBtnIndex == 1 ) {
				inProgressing = true;
				GameConnect.shared.DeleteAccount(onGameConnectDeleteAccount);
			} 
		});
		#endif
	}

	void onGameConnectDeleteAccount(bool success, string message)
	{
		inProgressing = false;

		if (success) {

			HIVEManager.shared.signOut((bool isSuccess, string errorCode) => {

				HIVEManager.shared.resetAgreement();
				HIVEManager.shared.isSetup = false;

				popup.show(SBSLocalization.PopupKey.DELETE_ACCOUNT_COMPLETE, null, null, new string [] { "OK" }, (int clickBtnIndex) =>{
					PlayerSettings.Instance ().reset ();
					homeManager.IsGameSignIn = false;
					homeManager.onSettingsClick (false);

					Debug.Log ("LoadScene \"Home\"");

					SceneManager.LoadScene("Home", LoadSceneMode.Single);
				});
				
			});

		} else {
			popup.show(SBSLocalization.PopupKey.DELETE_ACCOUNT_FAILED, message, null, new string [] { "OK" }, (int clickBtnIndex) =>{	
			});
		}
	}


	/*
	 * AuthV4.Helper SignOut.
	 * 게임 로그인 정보도 초기화하고 로그인 Scene으로 이동.
	 */
	void onHIVEManagerSignOut(bool success, string message)
	{
		Debug.Log ("onHIVEManagerSignOut");

		if (!success) {
			// 로그아웃 실패
			popup.show(SBSLocalization.PopupKey.HIVE_SIGNOUT_FAIL, message, null, new string[] {"OK"}, null);
		} else {
			// 로그아웃 성공
			PlayerSettings.Instance ().reset ();
			homeManager.IsGameSignIn = false;
			homeManager.onSettingsClick (false);
		}
	}


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

		#if UNITY_EDITOR
		onHIVEManagerSignOut(true, "Success");
		#else
		HIVEManager.shared.signOut(onHIVEManagerSignOut);
		#endif
	}
	/* SignOut end */


	void onHIVEManagerConnect(bool success, string message, bool moveToTitle)
	{
		Debug.Log ("onHIVEManagerConnect");

		if (success) {
			GameConnect.shared.SignIn(onGameConnectSignIn);

			if (moveToTitle) {	
				homeManager.onSettingsClick(false);
			}

		} else {
			popup.show(SBSLocalization.PopupKey.ACCOUNT_SYNC_FAILED, message, null, new string[] {"OK"}, (buttonIndex) => {
				if (moveToTitle) {
					homeManager.onSettingsClick(false);
				}
				uiInitialize();
			});
		}
	}

	void onGameConnectSignIn(bool success, string message)
    {
		homeManager.onGameConnectSignIn(success, message);
		uiInitialize();
    }

	void onHIVEManagerDisconnect(bool success, string message)
	{
		uiInitialize();

		Dictionary<AuthV4.ProviderType, AuthV4.ProviderInfo> providerInfo = AuthV4.getPlayerInfo().providerInfoData;

		if (!success) {
			popup.show(SBSLocalization.PopupKey.ACCOUNT_SYNC_FAILED, message, null, new string[] {"OK"}, null);
		} else if (providerInfo.Count <= 0) {
			popup.show(SBSLocalization.PopupKey.TRANSFERRED_GUEST_ACCOUNT, null, null, new string[] {"OK"}, null);
		}
	}


	private void diconnectEnable (AuthV4.ProviderType providerType)
	{
		Dictionary<AuthV4.ProviderType, AuthV4.ProviderInfo> providerInfo = AuthV4.getPlayerInfo().providerInfoData;

		if (providerInfo.Count <= 1) {
			popup.show(SBSLocalization.PopupKey.ACCOUNT_UNSYNC_LAST_IDP, null, null, new string[] { "Cancel" ,"OK" }, (int clickBtnIndex) => {
				if (clickBtnIndex == 1 ) {
					HIVEManager.shared.disconnect(providerType, onHIVEManagerDisconnect);
				} 
			});
			
		} else {
			HIVEManager.shared.disconnect(providerType, onHIVEManagerDisconnect);
		}
	}


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

		if (!enableGoogle) {
			buttonGoogle.GetComponent<Image>().sprite = spritePGIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.GOOGLE, onHIVEManagerConnect);

		} else {
			diconnectEnable(AuthV4.ProviderType.GOOGLE);
		}
	}


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

		if (!enableGooglePlayGames)
		{
			buttonGooglePlayGames.GetComponent<Image>().sprite = spritePGSIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.GOOGLE_PLAY_GAMES, onHIVEManagerConnect);
		}
		else
		{
			diconnectEnable(AuthV4.ProviderType.GOOGLE_PLAY_GAMES);
		}
	}


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

		if (!enableGameCenter) {

			#if UNITY_ANDROID
			// buttonOSPlatform.GetComponent<Image>().sprite = spritePGIng;
			// HIVEManager.shared.connect(AuthV4.ProviderType.GOOGLE, onHIVEManagerConnect);
			#elif UNITY_IOS
			buttonGameCenter.GetComponent<Image>().sprite = spriteGameCenterIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.APPLE, onHIVEManagerConnect);
			#endif

		} else {

			#if UNITY_ANDROID
			// diconnectEnable(AuthV4.ProviderType.APPLE);
			#elif UNITY_IOS
			diconnectEnable(AuthV4.ProviderType.APPLE);
			#endif
		}

	}


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

		if (!enableFacebook) {
			buttonFacebook.GetComponent<Image>().sprite = spriteFBIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.FACEBOOK, onHIVEManagerConnect);
		} else {
			diconnectEnable(AuthV4.ProviderType.FACEBOOK);
		}
	}


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

		if (!enableHive) {
			buttonHIVE.GetComponent<Image>().sprite = spriteHIVEIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.HIVE, onHIVEManagerConnect);
		} else {
			diconnectEnable(AuthV4.ProviderType.HIVE);
		}
	}


	public void onAppleSignInClick()
	{
		Debug.Log ("onAppleSignInClick");
		if (!enableAppleSignIn) {

			#if UNITY_ANDROID
			buttonAppleSignIn.GetComponent<Image>().sprite = spriteAppleSignInIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.SIGNIN_APPLE, onHIVEManagerConnect);
			
			#elif UNITY_IOS
			// iOS 13 미만인 경우 에러 팝업을 노출하도록 한다.
			string deviceVersion = UnityEngine.iOS.Device.systemVersion;
			string[] words = deviceVersion.Split('.');

			int deviceMajorVersion = int.Parse(words[0]);

			if (deviceMajorVersion < 13) {
				popup.show(SBSLocalization.PopupKey.NOT_SUPPORTED_APPLE_SIGNIN, null, null, new string [] {"Cancel"}, (int clickBtnIndex) => {

				});
			} else {
				buttonAppleSignIn.GetComponent<Image>().sprite = spriteAppleSignInIng;
				HIVEManager.shared.connect(AuthV4.ProviderType.SIGNIN_APPLE, onHIVEManagerConnect);
			}
			#endif

		} else {
			diconnectEnable(AuthV4.ProviderType.SIGNIN_APPLE);
		}

		
	}


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

		if (!enableLine) {
			buttonLine.GetComponent<Image>().sprite = spriteLineIng;
			HIVEManager.shared.connect(AuthV4.ProviderType.LINE, onHIVEManagerConnect);
		} else {
			diconnectEnable(AuthV4.ProviderType.LINE);
		}
	}
	/* conncet end */


	/* 1:1 문의 (inquiry) */
	void onHIVEManagerShowInquiry(bool success, string message)
	{
		Debug.Log ("onHIVEManagerShowInquiry : " + message);
	}

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

		HIVEManager.shared.showInquiry(onHIVEManagerShowInquiry);
	}
	/* 1:1 inquiry end */


	// /* cafe */
	// void onHIVEManagerShowCafe(bool success, string message)
	// {
	// 	Debug.Log ("onHIVEManagerShowCafe : " + message);
	// }

	// public void onCafeClick()
	// {
	// 	Debug.Log ("onCafeClick");

	// 	HIVEManager.shared.showCafe(onHIVEManagerShowCafe);
	// }
	// /* cafe end */


	/* Device Management */
	void onHIVEManagerShowDeviceManagement(bool success, string message)
	{
		Debug.Log ("onHIVEManagerShowDeviceManagement : " + message);
	}
	public void onDeviceManagementClick()
	{
		Debug.Log ("onDeviceManagementClick");

		HIVEManager.shared.showDeviceManagement(onHIVEManagerShowDeviceManagement);
	}
	/* Device Management end */


	/* terms */
	void onHIVEManagerShowTerms(bool success, string message)
	{
		Debug.Log ("onHIVEManagerShowTerms : " + message);
	}

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

		HIVEManager.shared.showTerms(onHIVEManagerShowTerms);
	}
	/* terms end */


	// Crash on Android
	public void onSettingTitleClick()
    {
		crashModeClickCount++;
#if UNITY_ANDROID
		if (crashModeClickCount > 5)
        {
			var message = new AndroidJavaObject("java.lang.String", "This is a test crash, ignore.");
			var exception = new AndroidJavaObject("java.lang.Exception", message);

			var looperClass = new AndroidJavaClass("android.os.Looper");
			var mainLooper = looperClass.CallStatic<AndroidJavaObject>("getMainLooper");
			var mainThread = mainLooper.Call<AndroidJavaObject>("getThread");
			var exceptionHandler = mainThread.Call<AndroidJavaObject>("getUncaughtExceptionHandler");
			exceptionHandler.Call("uncaughtException", mainThread, exception);
		}
#endif
	}
}
