using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GameNetwork;
using GameUtility;
using Game;

//	Summary
//		* 우편함 관리자
//		* 우편함 UI, 우편물 확인 및 수락 기능 제고
public class PostManager : MonoBehaviour {

	public HomeManager homeManager;

	public GameObject m_Panel;	// 우편함 panel

	public Loading loading;
	public Popup popup; // Popup
	

	public GameObject m_PostItem;	// 우편함 목록 item prefab.
	public GameObject m_PostItemContainer;	// 우편함 목록 container.
	
	private GameObject _instance; // single-ton 객체

	private int anrModeClickCount = 0;


	void Update () {
		if(Input.GetKeyDown(KeyCode.Escape))
		{
			loading.hide();
			if (popup.gameObject.activeSelf) {
				popup.dismiss();
			} else {
				homeManager.onPostboxClick(false);
			}
		}
	}

	// MARK: - Public

	/*
		우편함 UI 노출
	 */
	public void Show()
	{
		Debug.Log("PostManager.Show");

		reloadData();
	}

	/*
		우편함 reload 
	 */
	void reloadData()
	{
		Debug.Log("reloadData");
		
		loading.show();

#if !UNITY_EDITOR
		GameConnect.shared.CheckPostbox(onGameConnectCheckPostbox);
#else
		ClearOldItems();

		for (int i = 0; i < 20; i++) {
			GameObject item = Instantiate(m_PostItem) as GameObject;
			PostItem postItem = item.GetComponent<PostItem>();
			postItem.onPostItem += onRemoveItem;

			postItem.transform.parent	= m_PostItemContainer.transform;
			postItem.transform.localScale	= Vector3.one;
		}

#endif // !UNITY_EDITOR 
	}

	/*
		우편함 UI 닫기
	 */
	public void Dismiss()
	{
		Debug.Log("PostManager.Dismiss");

		loading.hide();
	}

	/*
		우편함 목록 갱신
	 */
	void UpdateList(List<Post> posts)
	{
		Debug.Log("UpdateList - " + posts);

		if (m_PostItemContainer == null) {
			Debug.Log("Post container is null.");
			return;
		}

		if (m_PostItemContainer != null
		&& m_PostItemContainer.activeSelf == false) {
			Debug.Log("Post container is inactive.");
			return;
		}

		ClearOldItems();

		if (posts != null && posts.Count > 0) {
			foreach (Post post in posts) {
				AddNewItem(post);
			}
		} else {
			popup.show(SBSLocalization.PopupKey.INBOX_IS_EMPTY, null, null, new string[] {"OK"}, null);
		}
	}

	/*
		우편함 목록 추가
	 */
	void AddNewItem(Post post)
	{
		Debug.Log("AddNewItem - " + post);

		GameObject item   = Instantiate(m_PostItem) as GameObject;
		PostItem postItem = item.GetComponent<PostItem>();
		postItem.post	  = post;
		postItem.onPostItem += onRemoveItem;

		postItem.transform.parent	= m_PostItemContainer.transform;
		postItem.transform.localScale	= Vector3.one;
	}

	/*
		우편함 목록 제거 delegate
	 */
	void onRemoveItem(PostItem item)
	{
		Debug.Log("onRemoveItem - " + item.ItemMessage.text);

#if !UNITY_EDITOR
		List<int> removePostItems = new List<int> ();
		removePostItems.Add(item.post.postId);

		GameConnect.shared.ReceivePost(removePostItems, onGameConnectReceivePost);
#endif // !UNITY_EDITOR
	}

	/*
		우편함 목록 복수 제거
	 */
	void RemoveAllItems()
	{
		Debug.Log("RemoveAllItems");

		PostItem []items = m_PostItemContainer.GetComponentsInChildren<PostItem>();

		Debug.Log("Count - " + items.Length);

		List<int> removePostItems = new List<int> ();

		foreach (PostItem item in items) {
			removePostItems.Add(item.post.postId);

			Destroy(item.gameObject, 1f);
		}

		GameConnect.shared.ReceivePost(removePostItems, onGameConnectReceivePost);
	}

	/*
		우편 UI 목록 단순 제거
	 */
	void ClearOldItems()
	{
		Debug.Log("ClearOldItems");

		PostItem []items = m_PostItemContainer.GetComponentsInChildren<PostItem>();

		foreach (PostItem item in items) {
			DestroyImmediate(item.gameObject);
		}
	}

	//====================================
	//	GameConnect 콜백 핸들러
	//====================================
	/*
		우편함 조회

		@param success 호출 결과 성공 여부
		@param message 응답 메시지
		@param posts 응답 받은 우편 목록
	 */
	void onGameConnectCheckPostbox(bool success, string message, List<Post> posts)
	{
		Debug.Log("onGameConnectCheckPostbox\nsuccess: " + success + "\nposts: " + posts);

		if (m_Panel == null) {
			Debug.Log("Panel is null.");
			return;
		}

		if (m_Panel != null 
		&& m_Panel.activeSelf == false) {
			Debug.Log("Postbox inactive Panel");
			return;
		}

		if (success) {
				UpdateList(posts);
		}
		else {
			popup.show(SBSLocalization.PopupKey.INBOX_CONNECTION_FAILED, message, null, new string[] {"OK"}, null);
		}

		loading.hide();
	}

	/*
		우편 수락

		@param success 호출 결과 성공 여부
		@param message 응답 메시지
		@param posts null
	 */
	void onGameConnectReceivePost(bool success, string message, List<Post> item)
	{
		Debug.Log("onGameConnectReceivePost");

		if (success == false) {
			return;
		}

		reloadData();
	}


	// ANR on Android
	public void onPostTitleClick()
	{
		anrModeClickCount++;
#if UNITY_ANDROID
		if (anrModeClickCount > 5)
		{
			AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
			activity.Call("runOnUiThread", new AndroidJavaRunnable(runOnUiThread));
		}
#endif
	}

	void runOnUiThread()
	{
		Debug.Log("I'm running on the Java UI thread!");
		while(true) {}
	}
}
