using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using hive;
using GameUtility;

//	Summary
//		* HIVE의 Promotion 항목을 노출하는 UI 기능
//		* HIVE에서 제공된 Link share, copy, QR Code 기능을 제공한다.

namespace GameCampaign
{
	/*
		캠페인 관리자.
	 */
	public class CampaignManager : MonoBehaviour
	{
		public HomeManager homeManager;
		public GameObject m_Panel; // Campaign UI panel.

		public GameObject m_CampaignItemPrefab; // Campaign Cell prefab.
		public GameObject m_CampaignItemContainer; // Campaign Cell container.

		public Popup popup; // Popup panel
		public Loading loading;

		private byte[] _qrcode; // HIVE Promotion
		private String _qrcodeUri;
		private string _inviteCommonLink; // Invite common link
		private string _inviteMessage;	// Invite Message

		// Campaign UI 노출 여부. (readonly)
		public bool IsShow {
			get {
				return (m_Panel.active == true);
			}
		}


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

		/*
			Campaign UI를 노출.
	 	*/
		public void Show ()
		{
			Debug.Log ("Show");

			m_Panel.SetActive (true);

			reloadData ();
		}

		/*
			Campaign UI를 닫는다.
		 */
		public void Dismiss ()
		{
			Debug.Log ("Dismiss");

			m_Panel.SetActive (false);
		}


		public int GetSDKLevel() {
			var clazz = AndroidJNI.FindClass("android/os/Build$VERSION");
			var fieldID = AndroidJNI.GetStaticFieldID(clazz, "SDK_INT", "I");
			var sdkLevel = AndroidJNI.GetStaticIntField(clazz, fieldID);
     	return sdkLevel;
		}

		/*
			Link Share 버튼 동작
		 */
		public void onShareButton ()
		{
			Debug.Log ("onShareButton - " + _inviteCommonLink);

			if (_inviteCommonLink == null) {
				popup.show(SBSLocalization.PopupKey.UNKNOWN_ERROR, null, null, new string[] {"OK"}, null);
			} 
			else {
				popup.show(SBSLocalization.PopupKey.INVITE_LINK_POPUP, _inviteCommonLink, null, new string[] { "Cancel", "Share" }, ShareButtonHandler);
			}
		}

		/*
			Link Share 버튼 동작 handler

			@param buttonIndex button index.
	 	*/
		void ShareButtonHandler (int buttonIndex)
		{
			Debug.Log ("ShareButtonHandler - " + buttonIndex);

			if (buttonIndex == 0) {
				// no operation.
			} else if (buttonIndex == 1) {
				Promotion.showUAShare(_inviteMessage, _inviteCommonLink, onHiveShareHandler);
				// PlatformHelper.shareText (_inviteCommonLink, onHiveShareHandler);
			}
		}

		/*
			Share HIVE handler

			@param result Share HIVE 동작 결과.
		*/
		void onHiveShareHandler (ResultAPI result)
		{
			Debug.Log ("onHiveShareHandler - " + result);

			if (result.isSuccess()) {
				popup.show(SBSLocalization.PopupKey.UA_SHARE_SUCCESS, null, null, new string[] {"OK"}, null);
			} else {
				popup.show(SBSLocalization.PopupKey.UA_SHARE_FAILED, result.code.ToString(), null, new string[] {"OK"}, null);
			}
		}

		/*
			QR Code 버튼 동작.
	 	*/
		public void onQRCodeButton ()
		{
			Debug.Log ("onQRCodeButton");

			if (_qrcode == null || _qrcodeUri == null) {
				popup.show(SBSLocalization.PopupKey.UNKNOWN_ERROR, null, null, new string[] {"OK"}, null);
			} 
			else {
				popup.show(SBSLocalization.PopupKey.INVITE_QR_POPUP, null, _qrcode, new string[] {"OK"}, qrCodeButtonHandler);
			}
		}

		void qrCodeButtonHandler(int buttonIndex)
		{
			Debug.Log ("qrCodeButtonHandler - " + buttonIndex);

			if (buttonIndex == 99) {
				PlatformShare platformShare = new PlatformShare();
				platformShare.setSharetype(PlatformShare.ShareType.MEDIA);
				platformShare.setText(_inviteMessage);
				platformShare.setMedia(new String[]{_qrcodeUri});

				PlatformHelper.share(platformShare, onHiveShareHandler);
			}
		}

		/*
			Campaign UI 내 항목을 재설정한다.
	 	*/
		void reloadData ()
		{
			Debug.Log ("reloadData");

			ClearOldItems ();

#if !UNITY_EDITOR
			loading.show();

			Promotion.getAppInvitationData(PromotionAppInvitationHandler);
#else
			_inviteCommonLink	= "http://example.com/invite/common/link";
			_inviteMessage = "Invite you into Step by Step with HIVE";
			_qrcode = System.Text.Encoding.UTF8.GetBytes ("");

			for (int i = 0; i < 20; i++) {
				AppInvitationCampaignStage campaign = new AppInvitationCampaignStage (null);
				campaign.title = "Campaign " + i;
				campaign.description = "Campaign Description " + i;
				campaign.count = 10;
				campaign.limit = i;
				campaign.goalCount = 3;
				campaign.goalTotal = 15;

				AddNewItem (campaign, true);
			}
#endif // !UNITY_EDITOR
		}

		/*
			HIVE 로부터 응답받은 Promotion 데이터 응답 handler.

			@param result 응답 결과
			@param appInvitationData Promotion data
	 	*/
		void PromotionAppInvitationHandler (ResultAPI result, AppInvitationData appInvitationData)
		{
			Debug.Log ("PromotionAppInvitationHandler:\nresult - " + result + "\nappInvitationData - " + appInvitationData);

			if (result.isSuccess () == false) {
				popup.show(SBSLocalization.PopupKey.UNKNOWN_ERROR, result.code.ToString(), null, new string[] {"OK"}, null);
			} else {
				_qrcode = appInvitationData.qrcode;
				_inviteCommonLink	= appInvitationData.inviteCommonLink;
				_inviteMessage 		= appInvitationData.inviteMessage;
				
				if ((_inviteMessage == null) || (_inviteMessage == "null")) {
					_inviteMessage = "";
				}


				foreach (AppInvitationCampaignStage campaign in appInvitationData.stageCampaignList) {
					AddNewItem (campaign, true);
				}

				foreach (AppInvitationCampaign campaign in appInvitationData.eachCampaignList) {
					AddNewItem (campaign, false);
				}

				/*
				 * QR Code
				 */
				if (_qrcode != null) {

					String qrcodeUrl = PlatformHelper.saveQrcodeToPng (_qrcode);

				#if !UNITY_EDITOR && UNITY_ANDROID
					// Android 8.0 이상인 경우
					if (GetSDKLevel() > 25) {

						_qrcodeUri = "content://" + Configuration.getAppId() + ".provider/external_files";

						String[] urlArray = qrcodeUrl.Split('/');
				
						for (int i=4; i<urlArray.Length; ++i) {
							_qrcodeUri += "/";
							_qrcodeUri += urlArray[i];
						}
					}
					else {
						_qrcodeUri = "file://" + qrcodeUrl;
					}

				#elif !UNITY_EDITOR && UNITY_IPHONE
					_qrcodeUri = "file://" + qrcodeUrl;
				#endif

				}

			}

			loading.hide();
		}

		/*
			캠페인 항목 선택시 동작.
	 	*/
		void onCampaignItem (CampaignItem item)
		{
			Debug.Log ("onCampaignItem" + item);

			// TODO: do something here...
			item.active = false;
		}

		/*
			모든 캠페인 항목에 대한 선택 처리.
	 	*/
		void onAllOnCampaignItem ()
		{
			// TODO: do something here...
		}

		/*
			UI상의 캠페인 항목을 clear 한다.
			캠페인 cell에 대한 clear로 실제 캠페인 기능의 처리는 아니다.
	 	*/
		void ClearOldItems ()
		{
			Debug.Log ("ClearOldItems");

			CampaignItem[] items = m_CampaignItemContainer.GetComponentsInChildren<CampaignItem> ();

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

		/*
			UI상의 캠페인 항목을 추가한다.

			@param Promotion의 캠페인 항목.
			@param isStageCampaign stage campaign 여부.
	 	*/
		void AddNewItem (AppInvitationCampaign campaign, bool isStageCampaign)
		{
			Debug.Log ("AddNewItem - " + campaign);

			GameObject item = Instantiate (m_CampaignItemPrefab) as GameObject;
			CampaignItem campaignItem = item.GetComponent<CampaignItem> ();
			campaignItem.onCampaignItem += onCampaignItem;

			campaignItem.setCampaign (campaign, isStageCampaign);

			campaignItem.transform.parent	= m_CampaignItemContainer.transform;
			campaignItem.transform.localScale	= Vector3.one;
		}
	}
}
