Triumph Experiential Game

Last Updated On – 12/FEB/2019
Development Duration – April 2018 to December 2018
Team – 5Force Team of J&F projects Gmbh
My Role – Team Lead and Game Developer
Current Status – iOS Test Flight Alpha Stage
Project Short Brief – A Gamified hybrid application for mobile platforms (iOS and Android) meant majorly for German customers of Triumph Gmbh company. The application’s main feature is its custom Photogrammetry & Augmented-Reality based Scan-Tech, and 3D-Enabled E-commerce features.
Technologies Used:
1. Unity 3D Game Engine
2. Adobe Photoshop
3. Visual Studio for C-Sharp Coding.
4. XCode for iOS Game Authoring.
5. Android Studio for Android Game Authoring.
6. Swift, Objective-C & Java language scripting for Camera and Scan-Tech plugin creation.

Triumph Hybrid Gamified Application Recording on iPhone 6S Plus.

Game Architecture Breakdown

Managers

1. Event Manager

Using UnityActions and UnityEvents, we created an Event Management System which allowed items in our projects to subscribe to events, and have events trigger actions in our games. This reduced dependencies and allowed easier maintenance of our project.

using System;
using System.Collections;
using System.Collections.Generic;
using Hotchform.Game.Triumph.API.DataModels;
using Hotchform.Game.Triumph.Utilities;
using UnityEngine;
using UnityEngine.Events;

/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       01/08/2018 11:41
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/

namespace Hotchform.Game.Triumph.Managers {
	public class EventManager : MonoBehaviour {

		#region Private Variables.
		private Dictionary<EventName, CustomEvent> _eventDictionary;

		private static EventManager _eventManager;
		#endregion

		#region Public Variables.
		public static EventManager instance {
			get {
				if(!_eventManager) {
					_eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;

					if(!_eventManager) {
						Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
					} else {
						_eventManager.Init();
					}
				}

				return _eventManager;
			}
		}
		#endregion

		#region Unity Methods.
		#endregion

		#region Initialization Methods.
		void Init() {
			if(_eventDictionary == null) {
				_eventDictionary = new Dictionary<EventName, CustomEvent>();
			}
		}
		#endregion

		#region Event Methods.
		public static void StartListening(EventName eventName, UnityAction<CustomEventPasser> listener) {
			CustomEvent thisEvent = null;
			if(instance._eventDictionary.TryGetValue(eventName, out thisEvent)) {
				thisEvent.AddListener(listener);
			} else {
				thisEvent = new CustomEvent();
				thisEvent.AddListener(listener);
				instance._eventDictionary.Add(eventName, thisEvent);
			}
		}

		public static void StopListening(EventName eventName, UnityAction<CustomEventPasser> listener) {
			if(_eventManager == null) return;
			CustomEvent thisEvent = null;
			if(instance._eventDictionary.TryGetValue(eventName, out thisEvent)) {
				thisEvent.RemoveListener(listener);
			}
		}

		public static void TriggerEvent(EventName eventName, CustomEventPasser param) {
			CustomEvent thisEvent = null;
			if(instance._eventDictionary.TryGetValue(eventName, out thisEvent)) {
				thisEvent.Invoke(param);
			}
		}
		#endregion
	}

	[SerializeField]
	public class CustomEvent : UnityEvent<CustomEventPasser> {
	}

	[SerializeField]
	public enum EventName {
		GS_DataUpdateSuccessfull,

		DB_AbortAllHttpClients,

		DB_DoSignIn,
		DB_DoSignUp,
		DB_DoSignOut,
		DB_DoAuthRefresh,
		DB_DoForgotPassword,
		DB_DoConfirmForgotPassword,
		DB_GetPublicProductsInfo,
		DB_GetAllConfigurables,
		DB_CreateUserConfigurable,
		DB_DeleteUserConfigurable,
		DB_GetAccountLoggedIn,
		DB_UpdateAccountLoggedIn,
		DB_GetAccountAll,
		DB_UpdateUserConfigurable,
		DB_UploadThreeDScanFile,
		DB_SendEmailOnScanUploadComplete,
		DB_SendInvitation,
		DB_DoDeleteAccount,
		DB_DoUploadUserProfile,
		DB_GetLoggedInUserCart,
		DB_AddLoggedInUserCart,
		DB_UpdateLoggedInUserCart,
		DB_DeleteLoggedInUserCart,
		DB_ApplyCouponToCart,
		DB_GetAllOrdersForLoggedInUser,
		DB_OrderCreateForLoggedInUser,
		DB_GetAllOffersForLoggedInUser,
		DB_GetPaypalURLComplete,
		Db_GetPaypalURLLoggedInUserProgress,
		DB_ConfirmPaypalPaymentComplete,
		Db_ConfirmPaypalURLLoggedInUserProgress,
		DB_FetchIPStackGeolocationAddress,


		UI_SignInProgress,
		UI_SignInComplete,
		UI_SignUpProgress,
		UI_SignUpComplete,
		UI_AuthRefreshComplete,
		UI_ForgotPasswordProgress,
		UI_ForgotPasswordComplete,
		UI_ConfirmForgotPasswordProgress,
		UI_ConfirmForgotPasswordComplete,
		UI_RegsiterComplete,
		UI_RegisterProgress,
		UI_GetPublicProductsInfo,
		UI_UserConfigurableCreationComplete,
		UI_UserConfigurableCreationProgress,
		UI_UserConfigurableDeleteComplete,
		UI_UserConfigurableDeleteProgress,
		UI_UserConfigurableUpdateComplete,
		UI_UserConfigurableUpdateProgress,
		UI_UploadThreeDScanFileComplete,
		UI_UploadThreeDScanFileProgress,
		UI_GetAccountLoggedInComplete,
		UI_UpdateAccountLoggedInComplete,
		UI_GetAccountAll,
		UI_SendInvitationComplete,
		UI_DeleteAccountProgress,
		UI_DeleteAccountComplete,
		UI_UploadProfileProgress,
		UI_UploadProfileComplete,
		UI_LoggedInUserCartGetComplete,
		UI_LoggedInUserCartGetProgress,
		UI_LoggedInUserCartAddComplete,
		UI_LoggedInUserCartAddProgress,
		UI_LoggedInUserCartUpdateComplete,
		UI_LoggedInUserCartUpdateProgress,
		UI_LoggedInUserCartDeleteComplete,
		UI_LoggedInUserCartDeleteProgress,
		UI_ApplyCouponToCartComplete,
		UI_ApplyCouponToCartProgress,
		UI_GetAllOrdersForLoggedInUserComplete,
		UI_GetAllOrdersForLoggedInUserProgress,
		UI_OrderCreateForLoggedInUserComplete,
		UI_OrderCreateForLoggedInUserProgress,
		UI_GetAllOffersForLoggedInUserComplete,
		UI_GetAllOffersForLoggedInUserProgress,
		UI_GetPaypalURLLoggedInUserComplete,
		UI_GetPaypalURLLoggedInUserProgress,
		UI_ConfirmPaypalPaymentComplete,
		UI_ConfirmPaypalPaymentProgress,
		UI_FetchIPStackGeolocationAddressComplete,
		UI_FetchIPStackGeolocationAddressProgress,
		UI_InternetReacheabilityUpdate,


		SM_LoadScene,

		LM_DataUpdateComplete_FromUI,
		LM_DataUpdateComplete_ToUI
	}

	[Serializable]
	public class CustomEventPasser {
	}

	[Serializable]
	public class AbortHttpClientsEventPasser : CustomEventPasser {
		public bool abortUploadScanAlso = false;

		public AbortHttpClientsEventPasser(bool abortUploadScanAlso) {
			this.abortUploadScanAlso = abortUploadScanAlso;
		}
	}

	public class DBSignInEventPasser : CustomEventPasser {
		public string username;
		public string email;
		public string password;

		public DBSignInEventPasser() {

		}

		public DBSignInEventPasser(string username, string email, string password) {
			this.username = username ?? throw new ArgumentNullException(nameof(username));
			this.email = email ?? throw new ArgumentNullException(nameof(email));
			this.password = password ?? throw new ArgumentNullException(nameof(password));
		}
	}

	[Serializable]
	public class DBForgotPasswordEventPasser : CustomEventPasser {
		public string username;
		public string newPassword;
		public string confirmationCode;
	}

	[Serializable]
	public class DBUserRegisterEventPasser : CustomEventPasser {
		public string firstName;
		public string lastName;
		public string email;
		public string password;
		public DBAddressEventPasser address;
	}

	[Serializable]
	public class DBAddressEventPasser : CustomEventPasser {
		public string pincode;
		public string street;
		public string place;

		public bool AllSet() {
			return !string.IsNullOrEmpty(pincode) && !string.IsNullOrEmpty(street) && !string.IsNullOrEmpty(place);
		}
	}

	[Serializable]
	public class DBPublicProductEventPasser : CustomEventPasser {
		public string langCode;
		public string productType;
		public string lastEvaluatedKeyId;
		public string id;

		public DBPublicProductEventPasser(string langCode, string productType, string lastEvaluatedKeyId, string id) {
			this.langCode = langCode ?? throw new ArgumentNullException(nameof(langCode));
			this.productType = productType ?? throw new ArgumentNullException(nameof(productType));
			this.lastEvaluatedKeyId = lastEvaluatedKeyId;
			this.id = id;
		}
	}

	[Serializable]
	public class DBLastConfigurableEventPasser : CustomEventPasser {
		public long startDate;
		public long endDate;
		public DBAddressEventPasser address;
		public float latitude;
		public float longitude;
		public List<string> selectedUserEmails;
		public string modelType;
		public string engraving;
	}

	[Serializable]
	public class DBUserConfigurableLastEvaluatedEventPasser : CustomEventPasser {
		public string productId;
		public string customerId;
		public long updatedAt;

		public DBUserConfigurableLastEvaluatedEventPasser(string productId, string customerId, long updatedAt) {
			this.productId = productId;
			this.customerId = customerId;
			this.updatedAt = updatedAt;
		}
	}

	[Serializable]
	public class DBUserConfigurableDeleteEventPasser : CustomEventPasser {
		public string productId;

		public DBUserConfigurableDeleteEventPasser(string productId) {
			this.productId = productId;
		}
	}

	[Serializable]
	public class DBGetAllAccountEventPasser : CustomEventPasser {
		public bool paginationRequired;
		public string lastEvalutedKeyUsername;

		public DBGetAllAccountEventPasser(bool paginationRequired, string lastEvalutedKeyUsername) {
			this.paginationRequired = paginationRequired;
			this.lastEvalutedKeyUsername = lastEvalutedKeyUsername;
		}
	}

	[Serializable]
	public class DBSendInvitaionEventPasser : CustomEventPasser {
		public string emailAddress;
		public string fullName;

		public DBSendInvitaionEventPasser(string emailAddress, string fullName) {
			this.emailAddress = emailAddress ?? throw new ArgumentNullException(nameof(emailAddress));
			this.fullName = fullName ?? throw new ArgumentNullException(nameof(fullName));
		}
	}

	[Serializable]
	public class DBProfileUpdateEventPasser : CustomEventPasser {
		public bool updateProfilePic;
		public string profileBase64;

		public DBProfileUpdateEventPasser(bool updateProfilePic, string profileBase64) {
			this.updateProfilePic = updateProfilePic;
			this.profileBase64 = profileBase64;
		}
	}

	[Serializable]
	public class DBAddCartEventPasser : CustomEventPasser {
		public string id;
		public string langType;
		public int quantity;
		public string priceCurrency;
		public float price;
		public string size;
		public string sizeUnit;
		public string product_id;
		public string configurationId;
		public float engravingCost;

		public DBAddCartEventPasser(string id, string langType, int quantity, string priceCurrency, float price, string size, string sizeUnit, string product_id, string configurationId, float engravingCost) {
			this.id = id ?? throw new ArgumentNullException(nameof(id));
			this.langType = langType ?? throw new ArgumentNullException(nameof(langType));
			this.quantity = quantity;
			this.priceCurrency = priceCurrency ?? throw new ArgumentNullException(nameof(priceCurrency));
			this.price = price;
			this.size = size;
			this.sizeUnit = sizeUnit ?? throw new ArgumentNullException(nameof(sizeUnit));
			this.product_id = product_id;
			this.configurationId = configurationId;
			this.engravingCost = engravingCost;
		}
	}

	[Serializable]
	public class DBUpdateCartEventPasser : CustomEventPasser {
		public string id;
		public string langType;
		public int quantity;
		public string configurationId;
		public string size;
		public string sizeUnit;
		public bool updateOnlyQuantity;

		public DBUpdateCartEventPasser(string id, string langType, int quantity, string size, string sizeUnit, string configurationId, bool updateOnlyQuantity) {
			this.id = id ?? throw new ArgumentNullException(nameof(id));
			this.langType = langType ?? throw new ArgumentNullException(nameof(langType));
			this.quantity = quantity;
			this.configurationId = configurationId;
			this.size = size;
			this.sizeUnit = sizeUnit ?? throw new ArgumentNullException(nameof(sizeUnit));
			this.updateOnlyQuantity = updateOnlyQuantity;
		}
	}

	[Serializable]
	public class DBApplyCouponEventPasser : CustomEventPasser {
		public string couponCode;
		public ApplyCouponAction action;

		public DBApplyCouponEventPasser(string couponCode, ApplyCouponAction action) {
			this.couponCode = couponCode ?? throw new ArgumentNullException(nameof(couponCode));
			this.action = action;
		}
	}

	[Serializable]
	public class DBGetAllOrdersEventPasser : CustomEventPasser {
		public bool paginationRequired;
		public string lastEvalutedKeyOrderNo;

		public DBGetAllOrdersEventPasser(bool paginationRequired, string lastEvalutedKeyOrderNo) {
			this.paginationRequired = paginationRequired;
			this.lastEvalutedKeyOrderNo = lastEvalutedKeyOrderNo;
		}
	}

	[Serializable]
	public class DBUploadThreeDScanFileEventPasser : CustomEventPasser {
		public string fileName;
		public string version;
		public string timestamp;
		public object dataToUpload;
		public string localURI;
		public UploadMediaType fileType;

		public DBUploadThreeDScanFileEventPasser(string fileName, string version, string timestamp, object dataToUpload, string localURI, UploadMediaType fileType) {
			this.fileName = fileName ?? throw new ArgumentNullException(nameof(fileName));
			this.version = version ?? throw new ArgumentNullException(nameof(version));
			this.timestamp = string.IsNullOrEmpty(timestamp) ? DateTime.UtcNow.GetUnixTime().ToString() : timestamp;
			this.dataToUpload = dataToUpload ?? throw new ArgumentNullException(nameof(dataToUpload));
			this.localURI = localURI ?? throw new ArgumentNullException(nameof(localURI));
			this.fileType = fileType;
		}
	}

	[Serializable]
    public class OnScanCompleteEmailFormFieldForEventPasser {
        public string scansS3URL;
        public string scansOwnerEmail;
        public string scansOwnerName;
		public string scansUploadedCount;
		public string scanFullID;
		public string scanID;
    }

    [Serializable]
    public class OnScanCompleteEmailEventPasser : CustomEventPasser {
        public List<string> toEmail = new List<string>();
        public string from;
        public string subject;
        public OnScanCompleteEmailFormFieldForEventPasser formField = new OnScanCompleteEmailFormFieldForEventPasser();
    }

	[Serializable]
	public class DBPaypalConfirmEventPasser : CustomEventPasser {
		public string payerId;
		public string paymentId;
		public float totalPrice;

		public DBPaypalConfirmEventPasser(string payerId, string paymentId, float totalPrice) {
			this.payerId = payerId ?? throw new ArgumentNullException(nameof(payerId));
			this.paymentId = paymentId ?? throw new ArgumentNullException(nameof(paymentId));
			this.totalPrice = totalPrice;
		}
	}

	[Serializable]
	public enum ApplyCouponAction {
		apply,
		delete
	}

	[Serializable]
	public class UIGenericEventPasser : CustomEventPasser {
		public string message;
		public bool isError;
		public bool isFailure;
		public CustomWebResponseProgress progressResponse;

		public UIGenericEventPasser(string message, bool isError, bool isFailure, CustomWebResponseProgress progressResponse = null) {
			this.message = message ?? throw new ArgumentNullException(nameof(message));
			this.isError = isError;
			this.isFailure = isFailure;
			this.progressResponse = progressResponse;
		}
	}

	[Serializable]
	public class UploadS3FileEventPasser : CustomEventPasser {
		public string message;
		public bool isError;
		public bool isFailure;
		public CustomWebResponseProgress progressResponse;
		public string localURI;
		public string remoteURI;
		public float sizeInMB;
		public float totalTimeTaken;

        public UploadS3FileEventPasser(string message, bool isError, bool isFailure, string localURI, string remoteURI, float sizeInMB, float totalTimeTaken, CustomWebResponseProgress progressResponse = null) {
            this.message = message ?? throw new ArgumentNullException(nameof(message));
            this.isError = isError;
            this.isFailure = isFailure;
            this.progressResponse = progressResponse;
            this.localURI = localURI;
            this.remoteURI = remoteURI;
            this.sizeInMB = sizeInMB;
            this.totalTimeTaken = totalTimeTaken;
        }
    }
}

2. Custom Scene Manager

Using Event Manager and Unity’s Scene Manager, this script manages the pre and post scene change logic that happens in the game. Anywhere in the game, any script or component doesn’t directly use Unity’s SceneManager to change or load a scene rather than they broadcast a scene to load using CustomScene enum and EventName.SM_LoadScene enum.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Code5.Game;
using Hotchform.Game.Triumph.Controllers;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
using UnityEngine.SceneManagement;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       02/08/2018 10:40
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using Hotchform.Game.Triumph.Managers.Testers;
using Hotchform.Game.Triumph.Utilities;
using UnityEngine.Profiling;
using System.Threading;
namespace Hotchform.Game.Triumph.Managers {
public class CustomSceneManager : MonoBehaviour {
#region Public Variables.
public static CustomSceneManager instance = null;
#endregion
#region Private Variables.
#endregion
#region Unity Methods.
//Awake is always called before any Start functions
void Awake() {
//Check if instance already exists
if(instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if(instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a CustomSceneManager.
Destroy(gameObject);
}
private void OnEnable() {
EventManager.StartListening(EventName.SM_LoadScene, OnSceneLoadRequest);
}
private void OnDisable() {
EventManager.StopListening(EventName.SM_LoadScene, OnSceneLoadRequest);
}
private void Start() {
Application.runInBackground = true;
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn() && !DataManager.instance.scanDataSO.info.HasAllDataUploaded) {
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.UploadingScreen));
}
Application.lowMemory += Application_LowMemoryCallback;
}
private void Update() {
// if(GameSettingsManager.instance.gameSettingsSO.info.currentGameScene == (int)CustomScene.SplashScreen) {
// 	//LoaderUtils.instance.ShowLoader();
// 	bool anyPPD = DataManager.instance.publicProductsSO.info.products.Any(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main") && DataManager.instance.publicProductsSO.info.products.Any(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_material");
// 	if(LanguageManager.instance.languageDataSO.info.languageDatum.Count > 0 && anyPPD && GameSettingsManager.instance.gameSettingsSO.info.currentGameScene != (int)CustomScene.StartScreen) {
// 		EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.StartScreen));
// 	}
// }
}
#endregion
#region Custom Methods.
void Application_LowMemoryCallback() {
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
Resources.UnloadUnusedAssets();
//StatusBarUtility.instance.SetStatus(GameConstants.lowMemoryWarning, StatusType.Warning, StatusDelay.SHORT);
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser((CustomScene)GameSettingsManager.instance.gameSettingsSO.info.currentGameScene));
}
private void OnSceneLoadRequest(CustomEventPasser customEventPasser) {
AssetBundle.UnloadAllAssetBundles(true);
Resources.UnloadUnusedAssets();
//Debug.Log("<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDelete.Count);
////long totalSize = 0;
//foreach(var item in ImageUtils.instantiatedTexturesToDelete) {
//	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
//	//Destroy(item);
//	DeleteInstantiatedTexture2D(item);
//}
////Debug.Log("<color=RED>Total Size of Deleted Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + totalSize);
////totalSize = 0;
//Debug.Log("<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDelete.Count);
//foreach(var item in ImageUtils.instantiatedSpritesToDelete) {
//	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
//	//Destroy(item);
//}
////Debug.Log("<color=RED>Total Size of Deleted Runtime Instantiated Sprite Objects on a Scene Change:</color> " + totalSize);
CustomLoadSceneEventPasser sceneEventPasser = (CustomLoadSceneEventPasser)customEventPasser;
AsyncOperation asyncOperation;
switch(sceneEventPasser.buildScene) {
case CustomScene.SplashScreen:
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Top);
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
EventManager.TriggerEvent(EventName.LM_DataUpdateComplete_FromUI, new CustomEventPasser());
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Top);
//GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Top);
}
break;
case CustomScene.StartScreen:
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Top);
}
break;
case CustomScene.AuthenticationScreen:
SceneChangerUIController.instance.FadeOutScene();
if(!DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.HomeScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.HomeScreen;
}
break;
case CustomScene.HomeScreen:
//SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
//LoaderUtils.instance.ShowLoader();
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.ProfileScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.AccountDeleteScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.TermsOfUseScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.PrivacyPolicyScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.TechnicalSettingsScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.MyAddressesScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.HuntingAndCollectingScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene);
// ImageUtils.instantiatedTexturesToDeletePostScene.Clear();
// ImageUtils.instantiatedTexturesToDeleteWithinScene.Clear();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
//LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.SetLoader(asyncOperation.progress);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.ShopScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
int sceneToLoad = (int)CustomScene.ShopScreen;
//if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct != null && DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.active) {
//	// User Configurable Product has been created on the server.
//	if(!string.IsNullOrEmpty(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.product_id)) {
//		// If UCP created but images not uploaded or, continue to ScannerSlider Screen.
//		if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder == null || !DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder.allUploadsCompleted) {
//			sceneToLoad = (int)CustomScene.ScanSliderScreen;
//		} // If UCP Created and all images uploaded correctly, go to materialisation Screen.
//		else if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder != null && DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder.allUploadsCompleted) {
//			//if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.selectedMaterialProduct.Count > 0)
//			//	sceneToLoad = (int)CustomScene.Individualisation;
//			//else
//			//	sceneToLoad = (int)CustomScene.MaterialisationScreen;
//		}
//	}
//}
asyncOperation = SceneManager.LoadSceneAsync(sceneToLoad, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.CartScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.UserConfigurablesScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.NewStoryScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.ScanSliderScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.GamePlayScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.ModelMarkingScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.UploadingScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.OrderCreationScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
case CustomScene.OrderResponseScreen:
SceneChangerUIController.instance.FadeOutScene();
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
asyncOperation = SceneManager.LoadSceneAsync((int)sceneEventPasser.buildScene, sceneEventPasser.loadSceneMode);
asyncOperation.allowSceneActivation = true;
asyncOperation.completed += (c) => {
LoaderUtils.instance.HideLoader();
SceneChangerUIController.instance.FadeInScene();
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)sceneEventPasser.buildScene;
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
// ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 	//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 	Destroy(item);
// 	//DeleteInstantiatedTexture2D(item);
// }
// Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
// ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
};
if(!asyncOperation.isDone) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
}
} else {
OnSceneLoadRequest(new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen, LoadSceneMode.Single));
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.AuthenticationScreen;
}
break;
default:
GameSettingsManager.instance.gameSettingsSO.info.currentGameScene = (int)CustomScene.IntroScreen;
break;
}
}
private void DeleteInstantiatedTexture2D(Texture2D texture2D) {
Thread thread = new Thread(() => Destroy(texture2D));
thread.Start();
}
#endregion
}
[Serializable]
public class CustomLoadSceneEventPasser : CustomEventPasser {
public CustomScene buildScene;
public LoadSceneMode loadSceneMode;
public CustomLoadSceneEventPasser(CustomScene buildScene, LoadSceneMode loadSceneMode = LoadSceneMode.Single) {
this.buildScene = buildScene;
this.loadSceneMode = loadSceneMode;
}
}
[Serializable]
public enum CustomScene {
IntroScreen = 0,
SplashScreen = 1,
StartScreen = 2,
AuthenticationScreen = 3,
HomeScreen = 4,
ProfileScreen = 5,
AccountDeleteScreen = 6,
TermsOfUseScreen = 7,
PrivacyPolicyScreen = 8,
TechnicalSettingsScreen = 9,
MyAddressesScreen = 10,
HuntingAndCollectingScreen = 11,
ShopScreen = 12,
CartScreen = 13,
UserConfigurablesScreen = 14,
NewStoryScreen = 15,
ScanSliderScreen = 16,
GamePlayScreen = 17,
UploadingScreen = 18,
ModelMarkingScreen = 19,
OrderCreationScreen = 20,
OrderResponseScreen = 21
}
}

3. Data Manager

This script is the core of our Game-Logic and is responsible for all data-flow between various systems and sub-systems using our Persistent ScribtableObjects based Data Management system. It also uses EventManager heavily.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Hotchform.Game.Triumph.API;
using Hotchform.Game.Triumph.API.DataModels;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.Managers.Testers;
using Hotchform.Game.Triumph.Utilities;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       31/07/2018 15:04
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using System.Text;
using System.Text.RegularExpressions;
using Fabric.Crashlytics;
using System.IO;
namespace Hotchform.Game.Triumph.Managers {
public class DataManager : MonoBehaviour {
#region Public Variables.
public static DataManager instance = null;
public UsersDataSO usersDataSO;
public TempDataSO tempDataSO;
public PublicProductsSO publicProductsSO;
public UserConfigurableProductSO userConfigurableProductSO;
public PrivacyPolicyDataSO privacyPolicyDataSO;
public TermsAndConditionDataSO termsAndConditionDataSO;
public UserCartSO userCartSO;
public UserOrdersSO userOrdersSO;
public UserOffersSO userOffersSO;
public ScanDataSO scanDataSO;
#endregion
#region Private Variables.
#endregion
#region Unity Methods.
//Awake is always called before any Start functions
void Awake() {
//Check if instance already exists
if(instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if(instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a DataManager.
Destroy(gameObject);
}
private void Start() {
//System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => {
//	return true;
//};
if(usersDataSO.info.currentLoggedInUserSettings != null && usersDataSO.info.currentLoggedInUserSettings.loggedIn) {
//EventManager.TriggerEvent(EventName.DB_GetAccountLoggedIn, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
}
}
private void OnEnable() {
EventManager.StartListening(EventName.DB_AbortAllHttpClients, OnAbortAllHttpClientsWithEvents);
EventManager.StartListening(EventName.DB_DoSignIn, OnSignInWithEvents);
EventManager.StartListening(EventName.DB_DoForgotPassword, OnForgotPasswordWithEvents);
EventManager.StartListening(EventName.DB_DoConfirmForgotPassword, OnConfirmForgotPasswordWithEvents);
EventManager.StartListening(EventName.DB_DoSignUp, OnSignUpWithEvents);
EventManager.StartListening(EventName.DB_GetPublicProductsInfo, OnGetPublicProductsInfoWithEvents);
EventManager.StartListening(EventName.GS_DataUpdateSuccessfull, UpdatePublicDataOnTrigger);
EventManager.StartListening(EventName.DB_GetAllConfigurables, GetAllConfigurableProductsWithEvents);
EventManager.StartListening(EventName.DB_CreateUserConfigurable, CreateConfigurableProductWithEvents);
EventManager.StartListening(EventName.DB_DeleteUserConfigurable, DeleteConfigurableProductWithEvents);
EventManager.StartListening(EventName.DB_GetAccountLoggedIn, OnGetAccountLoggedInWithEvents);
EventManager.StartListening(EventName.DB_GetAccountAll, OnGetAccountAllWithEvents);
EventManager.StartListening(EventName.DB_UpdateUserConfigurable, UpdateConfigurableProductWithEvents);
EventManager.StartListening(EventName.DB_UploadThreeDScanFile, OnUploadThreeDScanFileWithEvents);
EventManager.StartListening(EventName.DB_SendEmailOnScanUploadComplete, SendEmailOnScanUploadCompleteWithEvents);
EventManager.StartListening(EventName.DB_SendInvitation, SendInvitationWithEvents);
EventManager.StartListening(EventName.DB_DoSignOut, OnSignOutWithEvents);
EventManager.StartListening(EventName.DB_DoDeleteAccount, OnDeleteAccountWithEvents);
EventManager.StartListening(EventName.DB_DoUploadUserProfile, OnUserProfileUpdateWithEvents);
EventManager.StartListening(EventName.DB_GetLoggedInUserCart, OnGetLoggedInUserCartWithEvents);
EventManager.StartListening(EventName.DB_AddLoggedInUserCart, OnAddLoggedInUserCartWithEvents);
EventManager.StartListening(EventName.DB_UpdateLoggedInUserCart, OnUpdateLoggedInUserCartWithEvents);
EventManager.StartListening(EventName.DB_ApplyCouponToCart, OnApplyCouponToCartWithEvents);
EventManager.StartListening(EventName.DB_GetAllOrdersForLoggedInUser, OnGetAllOrdersWithEvents);
EventManager.StartListening(EventName.DB_OrderCreateForLoggedInUser, OnCreateOrderWithEvents);
EventManager.StartListening(EventName.DB_GetAllOffersForLoggedInUser, OnGetAllOffersWithEvents);
EventManager.StartListening(EventName.DB_GetPaypalURLComplete, OnGetPaypalURLWithEvents);
EventManager.StartListening(EventName.DB_ConfirmPaypalPaymentComplete, OnConfirmPaypalPaymentWithEvents);
EventManager.StartListening(EventName.DB_FetchIPStackGeolocationAddress, OnFetchIPStackGeolocation);
}
private void OnDisable() {
EventManager.StopListening(EventName.DB_AbortAllHttpClients, OnAbortAllHttpClientsWithEvents);
EventManager.StopListening(EventName.DB_DoSignIn, OnSignInWithEvents);
EventManager.StopListening(EventName.DB_DoForgotPassword, OnForgotPasswordWithEvents);
EventManager.StopListening(EventName.DB_DoConfirmForgotPassword, OnConfirmForgotPasswordWithEvents);
EventManager.StopListening(EventName.DB_DoSignUp, OnSignUpWithEvents);
EventManager.StopListening(EventName.DB_GetPublicProductsInfo, OnGetPublicProductsInfoWithEvents);
EventManager.StopListening(EventName.GS_DataUpdateSuccessfull, UpdatePublicDataOnTrigger);
EventManager.StopListening(EventName.DB_GetAllConfigurables, GetAllConfigurableProductsWithEvents);
EventManager.StopListening(EventName.DB_CreateUserConfigurable, CreateConfigurableProductWithEvents);
EventManager.StopListening(EventName.DB_DeleteUserConfigurable, DeleteConfigurableProductWithEvents);
EventManager.StopListening(EventName.DB_GetAccountLoggedIn, OnGetAccountLoggedInWithEvents);
EventManager.StopListening(EventName.DB_GetAccountAll, OnGetAccountAllWithEvents);
EventManager.StopListening(EventName.DB_UpdateUserConfigurable, UpdateConfigurableProductWithEvents);
EventManager.StopListening(EventName.DB_UploadThreeDScanFile, OnUploadThreeDScanFileWithEvents);
EventManager.StopListening(EventName.DB_SendEmailOnScanUploadComplete, SendEmailOnScanUploadCompleteWithEvents);
EventManager.StopListening(EventName.DB_SendInvitation, SendInvitationWithEvents);
EventManager.StopListening(EventName.DB_DoSignOut, OnSignOutWithEvents);
EventManager.StopListening(EventName.DB_DoDeleteAccount, OnDeleteAccountWithEvents);
EventManager.StopListening(EventName.DB_DoUploadUserProfile, OnUserProfileUpdateWithEvents);
EventManager.StopListening(EventName.DB_GetLoggedInUserCart, OnGetLoggedInUserCartWithEvents);
EventManager.StopListening(EventName.DB_AddLoggedInUserCart, OnAddLoggedInUserCartWithEvents);
EventManager.StopListening(EventName.DB_UpdateLoggedInUserCart, OnUpdateLoggedInUserCartWithEvents);
EventManager.StopListening(EventName.DB_ApplyCouponToCart, OnApplyCouponToCartWithEvents);
EventManager.StopListening(EventName.DB_GetAllOffersForLoggedInUser, OnGetAllOffersWithEvents);
EventManager.StopListening(EventName.DB_GetPaypalURLComplete, OnGetPaypalURLWithEvents);
EventManager.StopListening(EventName.DB_ConfirmPaypalPaymentComplete, OnConfirmPaypalPaymentWithEvents);
EventManager.StopListening(EventName.DB_FetchIPStackGeolocationAddress, OnFetchIPStackGeolocation);
}
private void OnApplicationQuit() {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(true));
}
#endregion
#region Custom Test Methods.
public void OnSignUpTest() {
//OnSignUp("[email protected]", "[email protected]", "[email protected]");
}
public void OnSignInTest() {
//OnSignIn("[email protected]", "[email protected]", "[email protected]");
EventManager.TriggerEvent(EventName.DB_DoSignIn, new DBSignInEventPasser("[email protected]", "[email protected]", "[email protected]"));
}
private void OnSignInWithEvents(CustomEventPasser customParams) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
DBSignInEventPasser dBSignInEventPasser = (DBSignInEventPasser)customParams;
OnSignIn(dBSignInEventPasser.username, dBSignInEventPasser.email, dBSignInEventPasser.password);
}
private void OnSignUpWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
DBUserRegisterEventPasser dBUserRegisterEventPasser = (DBUserRegisterEventPasser)customEventPasser;
OnSignUp(dBUserRegisterEventPasser);
}
public void OnAuthRefreshTest() {
if(usersDataSO.info.listOfUsers.users.Any(u => u.uuid == "[email protected]")) {
UserData userData = usersDataSO.info.listOfUsers.users.Find(u => u.uuid == "[email protected]");
OnAuthRefresh(userData);
} else {
Debug.LogError(string.Format("User with uuid: {0} not found, Creating one instead. Try hitting refresh test button again!", "[email protected]"));
OnSignInTest();
}
}
private void OnForgotPasswordWithEvents(CustomEventPasser customEventPasser) {
DBForgotPasswordEventPasser forgotPasswordEventPasser = (DBForgotPasswordEventPasser)customEventPasser;
OnForgotPassword(forgotPasswordEventPasser.username);
}
private void OnConfirmForgotPasswordWithEvents(CustomEventPasser customEventPasser) {
DBForgotPasswordEventPasser forgotPasswordEventPasser = (DBForgotPasswordEventPasser)customEventPasser;
OnConfirmForgotPassword(forgotPasswordEventPasser.username, forgotPasswordEventPasser.newPassword, forgotPasswordEventPasser.confirmationCode);
}
private void OnSignOutWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(true));
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
OnAbortAllHttpClientsWithEventsForSignOut(new AbortHttpClientsEventPasser(true), cA => {
usersDataSO.info.currentLoggedInUserSettings.rememberPassword = false;
usersDataSO.info.currentLoggedInUserSettings.loggedIn = false;
usersDataSO.info.currentLoggedInUserSettings.uuid = string.Empty;
userConfigurableProductSO.info = new UserConfigurableProductInfo();
userCartSO.info = new LoggedInUserCartInfo();
userOrdersSO.info = new UserOrdersInfo();
userOrdersSO.info.orders = new List<UserOrderData>();
userOffersSO.info = new UserOffersInfo();
userOffersSO.info.offers = new List<UserOfferData>();
tempDataSO.info.tempCartItems = null;
scanDataSO.info.Clear();
scanDataSO.info = new ScanInfo();
usersDataSO.info.listOfUsers = new ListOfUsers();
LoaderUtils.instance.HideLoader();
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
SaveAndLoadManager.instance.SaveAllData();
});
}
private void OnDeleteAccountWithEvents(CustomEventPasser customEventPasser) {
EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(true));
OnDeleteAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool);
}
private void OnUserProfileUpdateWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
DBProfileUpdateEventPasser eventPasser = (DBProfileUpdateEventPasser)customEventPasser;
OnUploadUserProfile(eventPasser.updateProfilePic, eventPasser.profileBase64, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid));
}
private void OnGetPublicProductsInfoWithEvents(CustomEventPasser customEventPasser) {
DBPublicProductEventPasser dBPublicProductEventPasser = (DBPublicProductEventPasser)customEventPasser;
GetPublicProducts(dBPublicProductEventPasser);
}
public void TestGetPublicProductsInfo() {
EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser("de", "main", null, null));
}
private void UpdatePublicDataOnTrigger(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(!uIGenericEventPasser.isError && !uIGenericEventPasser.isFailure) {
List<LanguageData> languageDatum = LanguageManager.instance.languageDataSO.info.languageDatum;
for(int i = 0; i < languageDatum.Count; i++) {
EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser(languageDatum[i].lang_code, "main", null, null));
EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser(languageDatum[i].lang_code, "material", null, null));
if(DataManager.instance.usersDataSO.IsAnyUserLoggedIn()) {
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
}
//EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser(languageDatum[i].lang_code, "box", null, null));
//EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser(languageDatum[i].lang_code, "threeDScan", null, null));
}
} else {
StatusBarUtility.instance.SetStatus(uIGenericEventPasser.message, StatusType.Error, StatusDelay.LONG);
}
}
private void GetAllConfigurableProductsWithEvents(CustomEventPasser customEventPasser) {
DBUserConfigurableLastEvaluatedEventPasser eventPasser = (DBUserConfigurableLastEvaluatedEventPasser)customEventPasser;
GetAllUserConfigurableProducts(eventPasser);
}
private void CreateConfigurableProductWithEvents(CustomEventPasser customEventPasser) {
DBLastConfigurableEventPasser dBLastConfigurableEventPasser = (DBLastConfigurableEventPasser)customEventPasser;
OnCreateUserConfigurableProduct(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBLastConfigurableEventPasser);
}
private void DeleteConfigurableProductWithEvents(CustomEventPasser customEventPasser) {
DBUserConfigurableDeleteEventPasser dBUserConfigurableDeleteEventPasser = (DBUserConfigurableDeleteEventPasser)customEventPasser;
OnDeleteUserConfigurable(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBUserConfigurableDeleteEventPasser.productId);
}
private void OnGetAccountLoggedInWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
OnGetAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), usersDataSO.info.currentLoggedInUserSettings.uuid);
}
private void UpdateConfigurableProductWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
OnUpdateUserConfigurableProduct(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid));
}
private void OnUploadThreeDScanFileWithEvents(CustomEventPasser customEventPasser) {
DBUploadThreeDScanFileEventPasser eventPasser = (DBUploadThreeDScanFileEventPasser)customEventPasser;
UploadThreeDScanImage(eventPasser.fileType, eventPasser.dataToUpload, eventPasser.localURI, new PreSignedURLFileUploadRequestBody(eventPasser.fileName, eventPasser.timestamp, eventPasser.version));
}
private void SendEmailOnScanUploadCompleteWithEvents(CustomEventPasser customEventPasser) {
OnScanCompleteEmailEventPasser eventPasser = (OnScanCompleteEmailEventPasser)customEventPasser;
OnScanCompleteEmailRequestBody requestBody = new OnScanCompleteEmailRequestBody {
toEmail = eventPasser.toEmail,
subject = eventPasser.subject,
from = eventPasser.from,
formField = new OnScanCompleteEmailFormField {
scanFullID = eventPasser.formField.scanFullID,
scanID = eventPasser.formField.scanID,
scansOwnerEmail = eventPasser.formField.scansOwnerEmail,
scansOwnerName = eventPasser.formField.scansOwnerName,
scansUploadedCount = eventPasser.formField.scansUploadedCount,
scansS3URL = eventPasser.formField.scansS3URL
}
};
SendEmailOnScanUploadComplete(requestBody);
}
private void OnGetAccountAllWithEvents(CustomEventPasser customEventPasser) {
DBGetAllAccountEventPasser dBGetAllAccountEventPasser = (DBGetAllAccountEventPasser)customEventPasser;
OnGetAccountAll(dBGetAllAccountEventPasser, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), usersDataSO.info.currentLoggedInUserSettings.uuid);
}
private void SendInvitationWithEvents(CustomEventPasser customEventPasser) {
DBSendInvitaionEventPasser dBSendInvitaionEventPasser = (DBSendInvitaionEventPasser)customEventPasser;
SendInvitationViaUserConfigurable(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBSendInvitaionEventPasser);
}
private void OnGetLoggedInUserCartWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
OnGetLoggedInUserCart();
}
private void OnAddLoggedInUserCartWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
DBAddCartEventPasser eventPasser = (DBAddCartEventPasser)customEventPasser;
//if(string.IsNullOrEmpty(eventPasser.product_id)) {
//	OnAddToCartNormal(new AddToCartNormalRequestBody(eventPasser.id, eventPasser.langType, eventPasser.quantity, eventPasser.priceCurrency, eventPasser.price, eventPasser.size, eventPasser.sizeUnit));
//} else {
//OnAddToCartNormal(new AddToCartRequestBody(eventPasser.id, eventPasser.langType, eventPasser.quantity, eventPasser.priceCurrency, eventPasser.price, eventPasser.size, eventPasser.sizeUnit, eventPasser.product_id));
OnAddToCartWithUserConfigurable(new AddToCartWithConfigurableRequestBody(eventPasser.id, eventPasser.langType, eventPasser.quantity, eventPasser.priceCurrency, eventPasser.price, eventPasser.size, eventPasser.sizeUnit, 
eventPasser.product_id, eventPasser.configurationId, eventPasser.engravingCost));
//}
}
private void OnUpdateLoggedInUserCartWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
DBUpdateCartEventPasser eventPasser = (DBUpdateCartEventPasser)customEventPasser;
// if(eventPasser.updateOnlyQuantity) {
// 	string normalJson = JsonUtility.ToJson(new UpdateCartNormalRequestBody(eventPasser.id, eventPasser.langType, eventPasser.quantity, eventPasser.size));
// 	OnUpdateCart(normalJson);
// } else {
string withConfigurableJson = JsonUtility.ToJson(new UpdateCartWithConfigurableRequestBody(eventPasser.id, eventPasser.langType, eventPasser.quantity, eventPasser.configurationId, eventPasser.size));
OnUpdateCart(withConfigurableJson);
//}
}
private void OnApplyCouponToCartWithEvents(CustomEventPasser customEventPasser) {
DBApplyCouponEventPasser eventPasser = (DBApplyCouponEventPasser)customEventPasser;
OnApplyCouponToCart(new ApplyCouponRequestBody(eventPasser.couponCode, nameof(ApplyCouponAction.apply)));
}
private void OnGetAllOrdersWithEvents(CustomEventPasser customEventPasser) {
DBGetAllOrdersEventPasser eventPasser = (DBGetAllOrdersEventPasser)customEventPasser;
OnGetAllOrders(eventPasser);
}
private void OnCreateOrderWithEvents(CustomEventPasser customEventPasser) {
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(false));
var tempOrderData = userOrdersSO.info.tempOrder;
CreateOrderRequestBody requestBody = new CreateOrderRequestBody {
orderStatus = tempOrderData.orderStatus,
orderType = tempOrderData.orderType,
orderComment = tempOrderData.orderComment,
copounCode = tempOrderData.copounCode,
priceCurrency = tempOrderData.priceCurrency,
orderFinalPrice = tempOrderData.orderFinalPrice,
orderDiscountAmount = tempOrderData.orderDiscountAmount,
calculatePrice = new CalculatePriceBody {
cartSubtotal = tempOrderData.calculatePrice.cartSubtotal,
totalShiping = tempOrderData.calculatePrice.totalShiping,
totaltax = tempOrderData.calculatePrice.totaltax
},
pay = new PayBody {
paymentId = tempOrderData.pay.paymentId.Length <= 5 ? "PAY-TEST-PAYPAL" : tempOrderData.pay.paymentId,
mode = tempOrderData.pay.mode,
name = tempOrderData.pay.name,
//accountno = tempOrderData.pay.accountno,
//expMonth = tempOrderData.pay.expMonth,
//expYear = tempOrderData.pay.expYear,
//securitycode = tempOrderData.pay.securitycode,
//couponcode = tempOrderData.pay.couponcode,
//remember = tempOrderData.pay.remember
},
ipaddress = tempOrderData.ipaddress,
deviceId = tempOrderData.deviceId,
address = new OrderAddressBody {
billAddress = new BillAddressBody {
firstName = tempOrderData.address.billAddress.firstName,
lastName = tempOrderData.address.billAddress.lastName,
pincode = tempOrderData.address.billAddress.pincode,
street = tempOrderData.address.billAddress.street,
place = tempOrderData.address.billAddress.place
},
shippingAddress = new ShippingAddressBody {
firstName = tempOrderData.address.shippingAddress.firstName,
lastName = tempOrderData.address.shippingAddress.lastName,
pincode = tempOrderData.address.shippingAddress.pincode,
street = tempOrderData.address.shippingAddress.street,
place = tempOrderData.address.shippingAddress.place
},
shippingAddressSame = tempOrderData.address.shippingAddressSame
}
};
requestBody.product = new List<ProductBody>();
foreach(var item in tempOrderData.product) {
var product = new ProductBody {
id = item.id,
lang_type = item.lang_type,
title = item.title,
quantity = item.quantity,
price = item.price,
size = item.size,
sizeUnit = item.sizeUnit,
product_id = item.product_id,
user_configure_product_id = item.user_configure_product_id
};
product.files = new List<FileBody>();
foreach(var fileItem in item.files) {
var file = new FileBody {
createdAt = fileItem.createdAt,
updatedAt = fileItem.updatedAt,
mediaFormat = fileItem.mediaFormat,
mediaType = fileItem.mediaType,
platformType = fileItem.platformType,
mediaUrl = fileItem.mediaUrl,
featuredType = fileItem.featuredType
};
product.files.Add(file);
}
requestBody.product.Add(product);
}
Debug.Log(string.Format("OnCreateOrder: {0}", JsonUtility.ToJson(requestBody)));
OnCreateOrder(requestBody);
}
private void OnGetAllOffersWithEvents(CustomEventPasser customEventPasser) {
OnGetAllOffers();
}
private void OnGetPaypalURLWithEvents(CustomEventPasser customEventPasser) {
GetPaypalURLForLoggedInUser();
}
private void OnConfirmPaypalPaymentWithEvents(CustomEventPasser customEventPasser) {
DBPaypalConfirmEventPasser eventPasser = (DBPaypalConfirmEventPasser)customEventPasser;
OnPaypalConfirmPayment(eventPasser);
}
private void OnFetchIPStackGeolocation(CustomEventPasser customEventPasser) {
OnFetchGeolocationAddressFromIP();
}
#endregion
#region API Controller Methods.
private void OnAbortAllHttpClientsWithEvents(CustomEventPasser customEventPasser) {
AbortHttpClientsEventPasser passer = (AbortHttpClientsEventPasser)customEventPasser;
APIController.instance.AbortAllHttpClients(passer.abortUploadScanAlso);
//StopAllCoroutines();
Debug.Log("Stopping all Network Processes...");
}
private void OnAbortAllHttpClientsWithEventsForSignOut(CustomEventPasser customEventPasser, Action<bool> completeAction = null) {
AbortHttpClientsEventPasser passer = (AbortHttpClientsEventPasser)customEventPasser;
APIController.instance.AbortAllHttpClients(passer.abortUploadScanAlso, cA => completeAction?.Invoke(cA));
//StopAllCoroutines();
Debug.Log("Stopping all Network Processes...");
}
#endregion
#region User Authentication Methods.
/*
OnPingServer(sR => {
if(sR) {
} else {
}
});
*/
private void OnSignUp(DBUserRegisterEventPasser dBUserRegisterEventPasser, bool isSilent = false) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.SignUpAsync(dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.password, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnSignUp Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
if(usersDataSO.CreateUserAuth(new UserAuthData(dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.password, false, "EMAIL"))) {
Debug.Log(string.Format("OnSignUp DB: User Created with uuid: {0}", dBUserRegisterEventPasser.email));
} else {
usersDataSO.UpdateUserAuth(new UserAuthData(dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.password, false, "EMAIL"));
}
tempDataSO.info.tempUsersAccountData.Add(dBUserRegisterEventPasser);
if(!isSilent)
EventManager.TriggerEvent(EventName.UI_SignUpComplete, new UIGenericEventPasser("Sign Up Success", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignUp Error: {0}, StatusCode: {1}", error, rA.statusCode));
if(!isSilent)
EventManager.TriggerEvent(EventName.UI_SignUpComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnSignUp(dBUserRegisterEventPasser, isSilent);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignUp Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
if(!isSilent)
EventManager.TriggerEvent(EventName.UI_SignUpComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnSignUp Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
if(!isSilent)
EventManager.TriggerEvent(EventName.UI_SignUpProgress, new UIGenericEventPasser("Registering, Please wait...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessful. Please Check your internet connection!"));
if(!isSilent)
EventManager.TriggerEvent(EventName.UI_SignUpComplete, new UIGenericEventPasser("Server Ping UnSucessful. Please Check your internet connection!", false, true));
}
});
}
private void OnSignIn(string username, string email, string password, bool silent = false) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.SignInAsync(email, password, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserSignInResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserSignInResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
if(!silent)
Debug.Log(string.Format("OnSignIn Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
usersDataSO.AddUserAuthResult(username, password, APIController.ConvertAuthResults(defaultWebResponse.ConvertedBody.AuthenticationResult));
if(usersDataSO.info.listOfUsers.users.Any(u => u.uuid == username)) {
if(tempDataSO.info.tempUsersAccountData.Any(t => t.email == username)) {
DBUserRegisterEventPasser dBUserRegisterEventPasser = tempDataSO.info.tempUsersAccountData.Find(t => t.email == username);
OnCreateAccount(GetIdTokenOfUser(dBUserRegisterEventPasser.email), dBUserRegisterEventPasser);
} else {
//GetAccount Data.
OnGetAccount(defaultWebResponse.ConvertedBody.AuthenticationResult.IdToken, username);
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Sign In Success", false, false));
EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
}
// TODO: Check this for new flow.
// if(tempDataSO.info.tempCartItems != null && tempDataSO.info.tempCartItems.Count > 0) {
// 	foreach(var item in tempDataSO.info.tempCartItems) {
// 		EventManager.TriggerEvent(EventName.DB_AddLoggedInUserCart, new DBAddCartEventPasser(item.productId, item.langType, item.quantity, item.priceCurrency, item.price, item.size, item.sizeUnit, item.userConfigurableId));
// 	}
// 	tempDataSO.info.tempCartItems.Clear();
// 	tempDataSO.info.tempCartItems = null;
// }
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Couldn't Find User with uuid {0} after successful signup. This shouldn't have happen!", username));
}
} else {
if(!silent)
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignIn Error: {0}, StatusCode: {1}", error, rA.statusCode));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnSignIn(username, email, password, silent);
} else {
if(!silent)
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignIn Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
if(!silent)
Debug.Log(string.Format("OnSignIn Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void OnSignIn(DBUserRegisterEventPasser dBUserRegisterEventPasser, bool silent = true) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.SignInAsync(dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.password, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserSignInResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserSignInResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
if(!silent)
Debug.Log(string.Format("OnSignIn Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
usersDataSO.AddUserAuthResult(dBUserRegisterEventPasser.email, dBUserRegisterEventPasser.password, APIController.ConvertAuthResults(defaultWebResponse.ConvertedBody.AuthenticationResult));
//TODO: Check this for new flow.
// if(tempDataSO.info.tempCartItems != null && tempDataSO.info.tempCartItems.Count > 0) {
// 	foreach(var item in tempDataSO.info.tempCartItems) {
// 		EventManager.TriggerEvent(EventName.DB_AddLoggedInUserCart, new DBAddCartEventPasser(item.productId, item.langType, item.quantity, item.priceCurrency, item.price, item.size, item.sizeUnit, item.userConfigurableId));
// 	}
// 	tempDataSO.info.tempCartItems.Clear();
// 	tempDataSO.info.tempCartItems = null;
// }
// EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
// EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
// EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Sign In Success", false, false));
// if(!silent)
// 	EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
} else {
if(!silent)
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignIn Error: {0}, StatusCode: {1}", error, rA.statusCode));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnSignIn(dBUserRegisterEventPasser, silent);
} else {
if(!silent)
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnSignIn Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
if(!silent)
Debug.Log(string.Format("OnSignIn Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
if(!silent)
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void OnAuthRefresh(UserData userData) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.RefreshAsync(userData.authResult.refreshToken, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserSignInResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserSignInResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnAuthRefresh Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
usersDataSO.RefreshUserAuthResult(userData.authData.username, userData.authResult.refreshToken, APIController.ConvertAuthResults(defaultWebResponse.ConvertedBody.AuthenticationResult));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAuthRefresh Error: {0}, StatusCode: {1}, For User ID: {2}, With Refresh Token: {3}", error, rA.statusCode, userData.authData.email, userData.authResult.refreshToken));
//StatusBarUtility.instance.SetStatus(error, StatusType.Error, StatusDelay.LONG);
}
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAuthRefresh Failure: {0}, StatusCode: {1}, For User ID: {2}, With Refresh Token: {3}", rA.meta.reason, rA.statusCode, userData.authData.email, userData.authResult.refreshToken));
OnAuthRefresh(userData);
//StatusBarUtility.instance.SetStatus(rA.meta.reason, StatusType.Error, StatusDelay.LONG);
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
}
});
}
private void OnAuthRefresh(UserData userData, Action<bool> responseAction) {
APIController.instance.OnPingServer(sR => {
if(sR) {
if(userData != null && userData.authResult != null && !string.IsNullOrEmpty(userData.authResult.refreshToken)) {
APIController.instance.RefreshAsync(userData.authResult.refreshToken, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserSignInResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserSignInResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnAuthRefresh Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
usersDataSO.RefreshUserAuthResult(userData.authData.username, userData.authResult.refreshToken, APIController.ConvertAuthResults(defaultWebResponse.ConvertedBody.AuthenticationResult));
responseAction(true);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAuthRefresh Error: {0}, StatusCode: {1}", error, rA.statusCode));
//StatusBarUtility.instance.SetStatus(error, StatusType.Error, StatusDelay.LONG);
responseAction(false);
}
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAuthRefresh Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
//StatusBarUtility.instance.SetStatus(rA.meta.reason, StatusType.Error, StatusDelay.LONG);
OnAuthRefresh(userData, responseAction);
}
});
}
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
responseAction(false);
}
});
}
private void OnForgotPassword(string username) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.ForgotPasswordAsync(username, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnForgotPassword Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ForgotPasswordComplete, new UIGenericEventPasser("Please check your email for Confirmation Code!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnForgotPassword Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ForgotPasswordComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnForgotPassword(username);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnForgotPassword Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ForgotPasswordComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnForgotPassword Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_ForgotPasswordProgress, new UIGenericEventPasser("Sending Confirmation Code to your email...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_ForgotPasswordComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
//OnForgotPassword(username);
}
});
}
private void OnConfirmForgotPassword(string username, string newPassword, string confirmationCode) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.ConfirmForgotPasswordAsync(username, newPassword, confirmationCode, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnConfirmForgotPassword Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmForgotPasswordComplete, new UIGenericEventPasser("New Password Set Successfully. Please try Logging In Now!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnConfirmForgotPassword Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmForgotPasswordComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnConfirmForgotPassword(username, newPassword, confirmationCode);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnConfirmForgotPassword Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmForgotPasswordComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnConfirmForgotPassword Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_ConfirmForgotPasswordProgress, new UIGenericEventPasser("Setting your new password...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_ConfirmForgotPasswordComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
public UserAccountData GetCurrentLoggedInAccountData() {
return usersDataSO.info.listOfUsers.users.Find(u => u.uuid == usersDataSO.info.currentLoggedInUserSettings.uuid).accountData;
}
public string GetIdTokenOfUser(string uuid) {
//if(usersDataSO.info.listOfUsers.users.Any(u => u.uuid == uuid))
if(!string.IsNullOrEmpty(usersDataSO.info.listOfUsers.users.Find(u => u.uuid == uuid).authResult.idToken))
return usersDataSO.info.listOfUsers.users.Find(u => u.uuid == uuid).authResult.idToken;
else
return null;
//else {
//	EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//	StatusBarUtility.instance.SetStatus("Due to Server Connectivity & Authentication Issues, we have logged you out. Please login again to continue!", StatusType.Warning, StatusDelay.NORMAL);
//	return null;
//}
}
#endregion
#region User Account Methods.
private void OnCreateAccount(string authToken, DBUserRegisterEventPasser dBUserRegisterEventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.CreateAccountAsync(dBUserRegisterEventPasser, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnCreateAccount Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
//EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Sign In Success", false, false));
if(usersDataSO.CreateUpdateUserAccount(dBUserRegisterEventPasser.email, ConvertAccountData(dBUserRegisterEventPasser))) {
Debug.Log(string.Format("OnCreateAccount DB: User Created with uuid: {0}", dBUserRegisterEventPasser.email));
} else {
Debug.Log(string.Format("OnCreateAccount DB: User Already Signed Up with uuid: {0}", dBUserRegisterEventPasser.email));
}
if(tempDataSO.info.tempUsersAccountData.Any(t => t.email == dBUserRegisterEventPasser.email)) {
tempDataSO.info.tempUsersAccountData.Remove(tempDataSO.info.tempUsersAccountData.Find(t => t.email == dBUserRegisterEventPasser.email));
}
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Sign In Success", false, false));
EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateAccount Failure: {0}, StatusCode: {1}", error, rA.statusCode));
StatusBarUtility.instance.SetStatus("Account Creation Failure, Please register again!", StatusType.Bug, StatusDelay.LONG);
// EventManager.TriggerEvent(EventName.DB_DoDeleteAccount, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Create Account failure!", false, true));
if(tempDataSO.info.tempUsersAccountData.Any(t => t.email == dBUserRegisterEventPasser.email)) {
tempDataSO.info.tempUsersAccountData.Remove(tempDataSO.info.tempUsersAccountData.Find(t => t.email == dBUserRegisterEventPasser.email));
}
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnCreateAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBUserRegisterEventPasser);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateAccount Failure: {0}, StatusCode: {1}", "Account Creation Failure, Please register again!", rA.statusCode));
StatusBarUtility.instance.SetStatus("Account Creation Failure, Please register again!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Create Account failure!", false, true));
if(tempDataSO.info.tempUsersAccountData.Any(t => t.email == dBUserRegisterEventPasser.email)) {
tempDataSO.info.tempUsersAccountData.Remove(tempDataSO.info.tempUsersAccountData.Find(t => t.email == dBUserRegisterEventPasser.email));
}
// EventManager.TriggerEvent(EventName.DB_DoDeleteAccount, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateAccount Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
StatusBarUtility.instance.SetStatus("Account Creation Failure, Please register again!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Create Account failure!", false, true));
if(tempDataSO.info.tempUsersAccountData.Any(t => t.email == dBUserRegisterEventPasser.email)) {
tempDataSO.info.tempUsersAccountData.Remove(tempDataSO.info.tempUsersAccountData.Find(t => t.email == dBUserRegisterEventPasser.email));
}
// EventManager.TriggerEvent(EventName.DB_DoDeleteAccount, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
// EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
//EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}, pA => {
Debug.Log(string.Format("OnCreateAccount Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
//EventManager.TriggerEvent(EventName.UI_SignInProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
}, authToken);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
//EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void OnDeleteAccount(string authToken, string userPoolId) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.DeleteAccountAsync(authToken, userPoolId, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnDeletAccount Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
usersDataSO.DeleteUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
EventManager.TriggerEvent(EventName.UI_DeleteAccountComplete, new UIGenericEventPasser("Account Deleted Successfully !", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnDeleteAccount Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_DeleteAccountComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnDeleteAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), userPoolId);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_DeleteAccountComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnDeleteAccount Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_DeleteAccountComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnDeleeAccount Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_DeleteAccountProgress, new UIGenericEventPasser("Deleting Your Account..", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_DeleteAccountComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void OnUploadUserProfile(bool updateProfilePic, string base64String, string authToken) {
APIController.instance.OnPingServer(sR => {
if(sR) {
var accountData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid).accountData;
UserProfileRequestBody requestBody = new UserProfileRequestBodyWithoutPic {
firstName = accountData.firstName,
lastName = accountData.lastName,
address = new UserFullAddressRequestBody {
billAddress = new UserAddressRequestBody {
firstName = accountData.address.billAddress.firstName,
lastName = accountData.address.billAddress.lastName,
street = accountData.address.billAddress.street,
place = accountData.address.billAddress.place,
pincode = accountData.address.billAddress.pincode
},
shippingAddress = new UserAddressRequestBody {
firstName = accountData.address.shippingAddress.firstName,
lastName = accountData.address.shippingAddress.lastName,
street = accountData.address.shippingAddress.street,
place = accountData.address.shippingAddress.place,
pincode = accountData.address.shippingAddress.pincode
},
shippingAddressSame = accountData.address.shippingAddressSame
},
active = accountData.active
};
((UserProfileRequestBodyWithoutPic)requestBody).pushNotification = new List<UserOffersOrdersPushNotificationRequestBody>();
foreach(var item in accountData.pushNotification) {
((UserProfileRequestBodyWithoutPic)requestBody).pushNotification.Add(new UserOffersOrdersPushNotificationRequestBody(item.offers, item.orders));
}
if(updateProfilePic) {
requestBody = new UserProfileRequestBodyWithPic((UserProfileRequestBodyWithoutPic)requestBody, base64String);
}
APIController.instance.UploadUserProfileAsync(updateProfilePic, requestBody, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnUploadUserProfile Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
//EventManager.TriggerEvent(EventName.DB_GetAccountLoggedIn, new CustomEventPasser());
EventManager.TriggerEvent(EventName.UI_UploadProfileComplete, new UIGenericEventPasser("Profile Uploaded Successfully!;" + updateProfilePic, false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUploadUserProfile Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadProfileComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnUploadUserProfile(updateProfilePic, base64String, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid));
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_UploadProfileComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUploadUserProfile Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadProfileComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnUploadUserProfile Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_UploadProfileProgress, new UIGenericEventPasser("Profile Update in Progress...", false, false, pA));
}, authToken);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UploadProfileComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", true, true));
}
});
}
private void OnGetAccount(string authToken, string uuid) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetAccountAsync(authToken, uuid, rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnGetAccount Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));

DefaultWebResponseData<UserGetAccountResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserGetAccountResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnGetAccount Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
//EventManager.TriggerEvent(EventName.UI_SignInComplete, new UIGenericEventPasser("Sign In Success", false, false));
if(usersDataSO.CreateUpdateUserAccount(uuid, ConvertAccountData(defaultWebResponse.ConvertedBody))) {
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser("Account/Profile Updated!", false, false));
} else {
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser(string.Format("User Not present in DB with uuid: {0}, Please report this bug to developer.", uuid), false, true));
}
} else {
if(defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.Forbidden || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.Unauthorized || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.BadRequest || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), uuid);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser(string.Format("Unable to refresh Account from Server."), false, true));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAccount Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser(error, true, false));
}
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAccount(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), uuid);
} else {
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser(string.Format("Unable to refresh Account from Server."), false, true));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAccount Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnGetAccount Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
//EventManager.TriggerEvent(EventName.UI_SignInProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_GetAccountLoggedInComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnGetAccountAll(DBGetAllAccountEventPasser dBGetAllAccountEventPasser, string authToken, string uuid) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetAccountAllAsync(dBGetAllAccountEventPasser.paginationRequired, dBGetAllAccountEventPasser.lastEvalutedKeyUsername, authToken, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserGetAccountAllResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserGetAccountAllResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnGetAccountAll Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
foreach(var item in defaultWebResponse.ConvertedBody.Items) {
usersDataSO.CreateUser(item.username);
if(usersDataSO.CreateUpdateUserAccount(item.username, ConvertAccountData(item))) {
Debug.Log(string.Format("OnGetAccountAll DB: User Account Data Updated with uuid: {0}", item.username));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAccountAll DB: User Not present in DB with uuid: {0}", item.username));
}
}
if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.username)) {
dBGetAllAccountEventPasser.paginationRequired = true;
dBGetAllAccountEventPasser.lastEvalutedKeyUsername = defaultWebResponse.ConvertedBody.LastEvaluatedKey.username;
EventManager.TriggerEvent(EventName.DB_GetAccountAll, dBGetAllAccountEventPasser);
} else {
EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser("Fetched all accounts!", false, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAccountAll(dBGetAllAccountEventPasser, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), uuid);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser("Unable to refresh Authentication Token!", false, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAccountAll Failure: {0}, StatusCode: {1}", error, rA.statusCode));
//EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser(error, false, true));
}
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAccountAll(dBGetAllAccountEventPasser, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), uuid);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser("Unable to refresh Authentication Token!", false, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAccountAll Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
//EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnGetAccountAll Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
//EventManager.TriggerEvent(EventName.UI_SignInProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_GetAccountAll, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void SendInvitationViaUserConfigurable(string authToken, DBSendInvitaionEventPasser dBSendInvitaionEventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.AddAccountViaUserConfigurableAsync(dBSendInvitaionEventPasser.fullName, dBSendInvitaionEventPasser.emailAddress, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("SendInvitationViaUserConfigurable Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_SendInvitationComplete, new UIGenericEventPasser("Invitaion Sent Successfully!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("SendInvitationViaUserConfigurable Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_SendInvitationComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
SendInvitationViaUserConfigurable(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBSendInvitaionEventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_SendInvitationComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("SendInvitationViaUserConfigurable Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_SendInvitationComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, authToken);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_SendInvitationComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", true, true));
}
});
}
private UserAccountData ConvertAccountData(DBUserRegisterEventPasser dBUserRegisterEventPasser) {
UserAccountData userAccountData = new UserAccountData(null, dBUserRegisterEventPasser.firstName, dBUserRegisterEventPasser.lastName, new UserFullAddress(new UserAddress(dBUserRegisterEventPasser.firstName, dBUserRegisterEventPasser.lastName, dBUserRegisterEventPasser.address.pincode, dBUserRegisterEventPasser.address.street, dBUserRegisterEventPasser.address.place), true));
userAccountData.pushNotification = new List<UserOffersOrdersPushNotification>();
userAccountData.pushNotification.Add(new UserOffersOrdersPushNotification(true, true));
userAccountData.active = true;
return userAccountData;
}
private UserAccountData ConvertAccountData(UserGetAccountResponseBody userGetAccountResponseBody) {
UserAccountData userAccountData;
if(userGetAccountResponseBody.profilePic == null || string.IsNullOrEmpty(userGetAccountResponseBody.profilePic.url))
userAccountData = new UserAccountData(null, userGetAccountResponseBody.firstName, userGetAccountResponseBody.lastName);
else
userAccountData = new UserAccountData(new UserProfilePic(userGetAccountResponseBody.profilePic.url, userGetAccountResponseBody.profilePic.createdAt, userGetAccountResponseBody.profilePic.updatedAt), userGetAccountResponseBody.firstName, userGetAccountResponseBody.lastName);
if(userGetAccountResponseBody.address != null && userGetAccountResponseBody.address.billAddress != null && userGetAccountResponseBody.address.shippingAddress != null) {
UserAddress billAddress = new UserAddress(userGetAccountResponseBody.address.billAddress.firstName, userGetAccountResponseBody.address.billAddress.lastName, userGetAccountResponseBody.address.billAddress.pincode, userGetAccountResponseBody.address.billAddress.street, userGetAccountResponseBody.address.billAddress.place);
UserAddress shippingAddress = new UserAddress(userGetAccountResponseBody.address.shippingAddress.firstName, userGetAccountResponseBody.address.shippingAddress.lastName, userGetAccountResponseBody.address.shippingAddress.pincode, userGetAccountResponseBody.address.shippingAddress.street, userGetAccountResponseBody.address.shippingAddress.place);
userAccountData.address = new UserFullAddress(billAddress, userGetAccountResponseBody.address.shippingAddressSame, shippingAddress);
}
if(userGetAccountResponseBody.pushNotification != null && userGetAccountResponseBody.pushNotification.Count > 0) {
List<UserOffersOrdersPushNotification> pushNotification = new List<UserOffersOrdersPushNotification>();
pushNotification.Add(new UserOffersOrdersPushNotification(userGetAccountResponseBody.pushNotification[0].offers, userGetAccountResponseBody.pushNotification[0].orders));
userAccountData.pushNotification = pushNotification;
}
userAccountData.email = userGetAccountResponseBody.email;
userAccountData.username = userGetAccountResponseBody.username;
userAccountData.createdAt = userGetAccountResponseBody.createdAt;
userAccountData.updatedAt = userGetAccountResponseBody.updatedAt;
userAccountData.active = userGetAccountResponseBody.active;
return userAccountData;
}
#endregion
#region PublicProducts Methods.
private void GetPublicProducts(DBPublicProductEventPasser dBPublicProductEventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetPublicProductsInfo(dBPublicProductEventPasser.langCode, dBPublicProductEventPasser.productType, dBPublicProductEventPasser.lastEvaluatedKeyId, dBPublicProductEventPasser.id, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<PublicProductsDataResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<PublicProductsDataResponseBody>>((string)rA.parsedData);
string error = defaultWebResponse.ConvertedBody.err;
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("GetPublicProducts Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
publicProductsSO.CheckAndUpdateInfo(ConvertPublicProductsInfo(defaultWebResponse.ConvertedBody));
if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.id)) {
EventManager.TriggerEvent(EventName.DB_GetPublicProductsInfo, new DBPublicProductEventPasser(dBPublicProductEventPasser.langCode, dBPublicProductEventPasser.productType, defaultWebResponse.ConvertedBody.LastEvaluatedKey.id, null));
} else {
EventManager.TriggerEvent(EventName.UI_GetPublicProductsInfo, new UIGenericEventPasser("Public Product fetched successfully!", false, false));
}
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPublicProducts Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetPublicProductsInfo, new UIGenericEventPasser(error, true, false));
StatusBarUtility.instance.SetStatus("Server Error in fetching Public Products!", StatusType.Warning, StatusDelay.LONG);
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
GetPublicProducts(dBPublicProductEventPasser);
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPublicProducts Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetPublicProductsInfo, new UIGenericEventPasser(rA.meta.reason, false, true));
StatusBarUtility.instance.SetStatus("Server Error in fetching Public Products!", StatusType.Warning, StatusDelay.LONG);
}
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPublicProducts: Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("GetPublicProducts: Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
}
});
}
private List<PublicProductData> ConvertPublicProductsInfo(PublicProductsDataResponseBody responseBody) {
List<PublicProductData> convertedData = new List<PublicProductData>();
foreach(var item in responseBody.Items) {
convertedData.Add(ConvertPublicProductData(item));
}
return convertedData;
}
private PublicProductData ConvertPublicProductData(PublicProductResponse productResponse) {
PublicProductData publicProductData = new PublicProductData {
size = productResponse.size,
productType = productResponse.productType,
assetType = productResponse.assetType,
sizeUnit = productResponse.sizeUnit,
engravingCost = productResponse.engravingCost,
basePrice = productResponse.basePrice,
createdAt = productResponse.createdAt,
updatedAt = productResponse.updatedAt,
lang_type = productResponse.lang_type,
currencyCode = productResponse.currencyCode,
description = productResponse.description,
price = productResponse.price,
id = productResponse.id,
title = productResponse.title,
showSizes = productResponse.showSizes,
sizes = new ProductSizes {
big = new ProductSizeInfo(productResponse.sizes.big.size, productResponse.sizes.big.price),
medium = new ProductSizeInfo(productResponse.sizes.medium.size, productResponse.sizes.medium.price),
small = new ProductSizeInfo(productResponse.sizes.small.size, productResponse.sizes.small.price)
}
};
publicProductData.files = new List<PublicProductFile>();
foreach(var item in productResponse.files) {
if(item.mediaType != FileMediaType.AssetBundle.ToString())
publicProductData.files.Add(new PublicProductFile(item.platformType, item.mediaUrl, item.mediaFormat, item.mediaType, item.featuredType, item.createdAt, item.updatedAt));
}
publicProductData.selectedMaterials = new List<SelectedMaterialProduct>();
foreach(var item in productResponse.selectedMaterials) {
publicProductData.selectedMaterials.Add(new SelectedMaterialProduct(item.lang_type, item.id));
}
return publicProductData;
}
#endregion
#region New Story Methods.
private void OnCreateUserConfigurableProduct(string authToken, DBLastConfigurableEventPasser dBLastConfigurableEventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.CreateUserConfigurableAsync(dBLastConfigurableEventPasser, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserConfigurableProductResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserConfigurableProductResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnCreateUserConfigurableProduct Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
UserConfigurableProductResponseBody userConfigurableProductResponseBody = defaultWebResponse.ConvertedBody;
userConfigurableProductSO.info.lastUserConfigurableProduct = ConvertUserConfigurable(userConfigurableProductResponseBody);
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationComplete, new UIGenericEventPasser("Configurable Product Created Successfully!", false, false));
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateUserConfigurableProduct Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnCreateUserConfigurableProduct(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), dBLastConfigurableEventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateUserConfigurableProduct Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnCreateUserConfigurableProduct Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationProgress, new UIGenericEventPasser("Creating User Configurable Product...", false, false, pA));
}, authToken);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UserConfigurableCreationComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", true, true));
}
});
}
private void OnDeleteUserConfigurable(string authToken, string productId) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.DeleteUserConfigurableAsync(authToken, productId, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnDeleteUserConfigurable Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteComplete, new UIGenericEventPasser("User Configurable Deleted Successfully", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnDeleteUserConfigurable Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnDeleteUserConfigurable(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), productId);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnDeleteUserConfigurable Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnDeleteUserConfigurable Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteProgress, new UIGenericEventPasser("Deleting User Configurable..", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UserConfigurableDeleteComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", false, true));
}
});
}
private void OnUpdateUserConfigurableProduct(string authToken) {
APIController.instance.OnPingServer(sR => {
if(sR) {
var lastConfigurable = userConfigurableProductSO.info.lastUserConfigurableProduct;
UpdateUserConfigurableRequestBody requestBody = new UpdateUserConfigurableRequestBody {
product_id = lastConfigurable.product_id,
dateAndTime = new DateAndTimeBody(lastConfigurable.dateAndTime.startDate, lastConfigurable.dateAndTime.endDate),
address = new AddressBody(lastConfigurable.address.address, lastConfigurable.address.plz, lastConfigurable.address.ort, new GpsLocationBody(lastConfigurable.address.gpsLocation.lat, lastConfigurable.address.gpsLocation.lang)),
people = lastConfigurable.people,
productType = lastConfigurable.productType,
oldthreeDscanFolder = new OldthreeDscanFolderResponseBody(lastConfigurable.oldthreeDscanFolder.timestamp, lastConfigurable.oldthreeDscanFolder.version),
engraving = string.IsNullOrEmpty(lastConfigurable.engraving) ? "NO ENGRAVING" : lastConfigurable.engraving,
active = lastConfigurable.active
};
requestBody.markOnImage = new List<MarkOnImageResponseBody>();
foreach(var item in lastConfigurable.markOnImage) {
requestBody.markOnImage.Add(new MarkOnImageResponseBody(item.xaxis, item.yaxis));
}
requestBody.threeDscanFile = new List<ThreeDscanFileResponseBody>();
foreach(var item in lastConfigurable.threeDscanFile) {
requestBody.threeDscanFile.Add(new ThreeDscanFileResponseBody(item.mediaType, item.mediaFormat, item.mediaUrl, item.platformType, DateTime.UtcNow.GetUnixTime(), DateTime.UtcNow.GetUnixTime()));
}
//requestBody.selectedMaterialProduct = new List<SelectedMaterialProductResponseBody>();
//foreach(var item in lastConfigurable.selectedMaterialProduct) {
//	requestBody.selectedMaterialProduct.Add(new SelectedMaterialProductResponseBody(item.lang_type, item.id));
//}
APIController.instance.UpdateUserConfigurableAsync(requestBody, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<UserConfigurableProductResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<UserConfigurableProductResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnUpdateUserConfigurableProduct Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
//UserConfigurableProductResponseBody userConfigurableProductResponseBody = defaultWebResponse.ConvertedBody;
//userConfigurableProductSO.lastUserConfigurableProductInfo = ConvertUserConfigurable(userConfigurableProductResponseBody);
//EventManager.TriggerEvent(EventName.)
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("Configurable Product Created Successfully!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUpdateUserConfigurableProduct Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnUpdateUserConfigurableProduct(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid));
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
// Use Arpit's method after merging.
//usersDataSO.info.currentLoggedInUserSettings = null;
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUpdateUserConfigurableProduct Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnUpdateUserConfigurableProduct Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateProgress, new UIGenericEventPasser("Creating User Configurable Product...", false, false, pA));
}, authToken);
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("Please check your Internet Connection again. Couldn't ping the server.", true, true));
}
});
}
private void GetAllUserConfigurableProducts(DBUserConfigurableLastEvaluatedEventPasser eventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetAllUserConfigurableProductsAsync(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), eventPasser.productId, eventPasser.updatedAt, rA => {
Debug.Log(string.Format("GetAllUserConfigurableProducts Actual: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
if(rA.meta.isSuccess) {
DefaultWebResponseData<GetAllUserConfigurableProductsResponseBody> defaultWebResponse;
string error = "Server Error";
try {
defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<GetAllUserConfigurableProductsResponseBody>>((string)rA.parsedData);
error = defaultWebResponse.ConvertedBody.err;
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("GetAllUserConfigurableProducts Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
//if(userConfigurableProductSO.info.allUserConfigurableProducts.Count > 0 && userConfigurableProductSO.info.allUserConfigurableProducts.Count < 11) {
//	DateTime dbDateTime = DateUtils.GetEpochDateTime(userConfigurableProductSO.info.allUserConfigurableProducts.Last().updatedAt);
//	DateTime remoteDateTime = DateUtils.GetEpochDateTime(defaultWebResponse.ConvertedBody.Items.Last().updatedAt);
//	userConfigurableProductSO.info.lastUpdatedAt = defaultWebResponse.ConvertedBody.Items.Last().updatedAt;
//	if(remoteDateTime < dbDateTime) {
//		userConfigurableProductSO.CheckAndUpdateAllConfigurables(defaultWebResponse.ConvertedBody.Count, ConvertAllUserConfigurables(defaultWebResponse.ConvertedBody));
//		if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id)) {
//			EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.cudtomer_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.updatedAt));
//		}
//	}
//} else if(userConfigurableProductSO.info.allUserConfigurableProducts.Count > 11) {
//	DateTime dbDateTime = DateUtils.GetEpochDateTime(userConfigurableProductSO.info.allUserConfigurableProducts.First().updatedAt);
//	DateTime remoteDateTime = DateUtils.GetEpochDateTime(defaultWebResponse.ConvertedBody.Items.First().updatedAt);
//	userConfigurableProductSO.info.lastUpdatedAt = defaultWebResponse.ConvertedBody.Items.First().updatedAt;
//	if(remoteDateTime > dbDateTime) {
//		userConfigurableProductSO.CheckAndUpdateAllConfigurables(defaultWebResponse.ConvertedBody.Count, ConvertAllUserConfigurables(defaultWebResponse.ConvertedBody));
//		//if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id)) {
//		//	EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.cudtomer_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.updatedAt));
//		//}
//	}
//} else {
//	userConfigurableProductSO.CheckAndUpdateAllConfigurables(defaultWebResponse.ConvertedBody.Count, ConvertAllUserConfigurables(defaultWebResponse.ConvertedBody));
//	if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id)) {
//		EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.cudtomer_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.updatedAt));
//	}
//}
userConfigurableProductSO.CheckAndUpdateAllConfigurables(defaultWebResponse.ConvertedBody.Count, ConvertAllUserConfigurables(defaultWebResponse.ConvertedBody));
if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id)) {
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(defaultWebResponse.ConvertedBody.LastEvaluatedKey.product_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.cudtomer_id, defaultWebResponse.ConvertedBody.LastEvaluatedKey.updatedAt));
} else {
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("All scans fetched successfully!", false, false));
}
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetAllUserConfigurableProducts Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser(error, true, false));
}
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
} catch(Exception exp) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetAllUserConfigurableProducts Exception: {0}, Data: {1}", exp.Message, (string)rA.parsedData));
GetAllUserConfigurableProducts(eventPasser);
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
GetAllUserConfigurableProducts(eventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {//if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetAllUserConfigurableProducts Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
//} else {
//	GetAllUserConfigurableProducts(eventPasser);
//}
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
}
});
}
private void SendEmailOnScanUploadComplete(OnScanCompleteEmailRequestBody requestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.SendEmailOnScanUploadCompleteAsync(requestBody, rA => {
Debug.Log(string.Format("SendEmailOnScanUploadComplete Actual: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
if(rA.meta.isSuccess) {
Debug.Log("SendEmailOnScanUploadComplete-> Email Sent Successfully!");
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("SendEmailOnScanUploadComplete Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY, true);
}
});
}
private void UploadThreeDScanImage(UploadMediaType uploadMediaType, object dataToUpload, string localURI, PreSignedURLFileUploadRequestBody uploadRequestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetPreSignedURLFromS3(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), uploadRequestBody, rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<PreSignedURLFromS3ResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<PreSignedURLFromS3ResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
//Debug.Log(string.Format("GetPreSignedURLFromS3 Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
APIController.instance.OnPingServer(sR2 => {
if(sR2) {
APIController.instance.UploadFileByBytes(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), defaultWebResponse.ConvertedBody.url, dataToUpload, uploadMediaType, rA2 => {
if(rA2.meta.isSuccess) {
if(string.IsNullOrEmpty(rA2.meta.reason)) {
//Debug.Log(string.Format("UploadThreeDScanImage Success: {0}, StatusCode: {1}", "Successfully Uploaded Image!", rA2.statusCode));
string url = defaultWebResponse.ConvertedBody.url.Split('?')[0];
DataManager.instance.userConfigurableProductSO.AddThreeDScanData(url, Application.version + "b");
string otherData = (string)rA2.otherData;
string[] dataSplit = otherData.Split(',');
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser("File uploaded successfully!", false, false, localURI, defaultWebResponse.ConvertedBody.url, float.Parse(dataSplit[0]), float.Parse(dataSplit[1])));// new UIGenericEventPasser(localURI + ";" + defaultWebResponse.ConvertedBody.url, false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("UploadThreeDScanImage Error: {0}, StatusCode: {1}", rA2.meta.reason, rA2.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser(rA2.meta.reason, true, false, string.Empty, string.Empty, 0f, 0f));
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
}
} else {
if(rA2.statusCode == System.Net.HttpStatusCode.Forbidden || rA2.statusCode == System.Net.HttpStatusCode.Unauthorized || rA2.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
//UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser("Unable to refresh Authentication Token!", true, false, string.Empty, string.Empty, 0f, 0f));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("UploadThreeDScanImage Failure: {0}, StatusCode: {1}", string.IsNullOrEmpty(rA2.meta.reason) ? (string)rA2.parsedData : rA2.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser(rA.meta.reason, false, true, string.Empty, string.Empty, 0f, 0f));
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
}
}
}, pA2 => {
//Debug.Log(string.Format("UploadThreeDScanImage Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA2.progress, pA2.contentLength, pA2.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileProgress, new UploadS3FileEventPasser("Uploading 3D Scan Image...", false, false, string.Empty, string.Empty, 0f, 0f, pA2));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true, string.Empty, string.Empty, 0f, 0f));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPreSignedURLFromS3 Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser(error, true, false, string.Empty, string.Empty, 0f, 0f));
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
//UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser("Unable to refresh Authentication Token!", true, false, string.Empty, string.Empty, 0f, 0f));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPreSignedURLFromS3 Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser(rA.meta.reason, false, true, string.Empty, string.Empty, 0f, 0f));
UploadThreeDScanImage(uploadMediaType, dataToUpload, localURI, uploadRequestBody);
}
}
}, pA => {
//Debug.Log(string.Format("GetPreSignedURLFromS3 Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
//EventManager.TriggerEvent(EventName.UI_UserConfigurableUpdateComplete, new UIGenericEventPasser("Creating User Configurable Product...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_UploadThreeDScanFileComplete, new UploadS3FileEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true, string.Empty, string.Empty, 0f, 0f));
}
});
}
private UserConfigurableProductData ConvertUserConfigurable(UserConfigurableProductResponseBody responseBody) {
UserConfigurableProductData lastUserConfigurableProductInfo = new UserConfigurableProductData {
customer_id = responseBody.customer_id,
product_id = responseBody.product_id,
dateAndTime = new DateAndTime(responseBody.dateAndTime.startDate, responseBody.dateAndTime.endDate),
address = new Address(responseBody.address.address, responseBody.address.plz, responseBody.address.ort, new GpsLocation(responseBody.address.gpsLocation.lat, responseBody.address.gpsLocation.lang)),
people = responseBody.people,
productType = responseBody.productType,
oldthreeDscanFolder = new OldthreeDscanFolder(responseBody.oldthreeDscanFolder.timestamp, responseBody.oldthreeDscanFolder.version),
engraving = responseBody.engraving,
active = responseBody.active,
createdAt = responseBody.createdAt,
updatedAt = responseBody.updatedAt
};
lastUserConfigurableProductInfo.markOnImage = new List<MarkOnImage>();
foreach(var item in responseBody.markOnImage) {
lastUserConfigurableProductInfo.markOnImage.Add(new MarkOnImage(item.xaxis, item.yaxis));
}
lastUserConfigurableProductInfo.threeDscanFileCount = responseBody.threeDscanFileCount;
if(responseBody.threeDscanFileCount > 0)
lastUserConfigurableProductInfo.oldthreeDscanFolder.allUploadsCompleted = true;
lastUserConfigurableProductInfo.threeDscanFile = new List<ThreeDscanFile>();
foreach(var item in responseBody.threeDscanFile) {
lastUserConfigurableProductInfo.threeDscanFile.Add(new ThreeDscanFile(item.mediaType, item.mediaFormat, item.mediaUrl, item.platformType, item.createdAt, item.updatedAt));
}
return lastUserConfigurableProductInfo;
}
private List<UserConfigurableProductData> ConvertAllUserConfigurables(GetAllUserConfigurableProductsResponseBody responseBody) {
List<UserConfigurableProductData> returnList = new List<UserConfigurableProductData>();
foreach(var item in responseBody.Items) {
returnList.Add(ConvertUserConfigurable(item));
}
return returnList;
}
#endregion
#region Cart & Order Methods.
private void OnGetLoggedInUserCart() {
APIController.instance.OnPingServer(sR => {
if(sR) {
string authToken = GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
if(string.IsNullOrEmpty(authToken)) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetLoggedInUserCart();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("GetCart Auth Token: " + GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid));
APIController.instance.GetLoggedInUserCartAsync(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
try {
Debug.Log(string.Format("<color=blue>OnGetLoggedInUserCart Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
DefaultWebResponseData<GetCartResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<GetCartResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error) && defaultWebResponse != null) {
Debug.Log(string.Format("OnGetLoggedInUserCart Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
userCartSO.info = ConvertUserCart(defaultWebResponse.ConvertedBody);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser("Current Cart Fetched/Updated Successfully!", false, false));
} else {
Debug.Log(string.Format("OnGetLoggedInUserCart Error: {0}, StatusCode: {1}", defaultWebResponse.body, defaultWebResponse.statusCode));
if(defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.Forbidden || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.Unauthorized || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.BadRequest || defaultWebResponse.statusCode == (int)System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetLoggedInUserCart();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetLoggedInUserCart Error: {0}, StatusCode: {1}", error, rA.statusCode));
//if(userCartSO.info != null)
//userCartSO.info = null;
OnGetLoggedInUserCart();
//EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser(error, true, false));
}
}
} catch(Exception exp) {
Debug.Log(exp);
Crashlytics.RecordCustomException("GetLoggedInCart JSON Exception with Response: " + (string)rA.parsedData, exp.Message, exp.StackTrace);
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetLoggedInUserCart();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetLoggedInUserCart Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
OnGetLoggedInUserCart();
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnGetLoggedInUserCart Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
}
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartGetComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnAddToCartNormal(AddToCartRequestBody requestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.AddToCartNormalAsync(requestBody, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnAddToCartNormal Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnAddToCartNormal Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Current Cart Fetched/Updated Successfully!", false, false));
//EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAddToCartNormal Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnAddToCartNormal(requestBody);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAddToCartNormal Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnAddToCartNormal Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnAddToCartWithUserConfigurable(AddToCartWithConfigurableRequestBody requestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.AddToCartWithUserConfigurableAsync(requestBody, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnAddToCartWithUserConfigurable Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnAddToCartWithUserConfigurable Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Current Cart Fetched/Updated Successfully!", false, false));
//EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAddToCartWithUserConfigurable Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnAddToCartWithUserConfigurable(requestBody);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnAddToCartWithUserConfigurable Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnAddToCartWithUserConfigurable Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartAddComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnUpdateCart(string requestBodyJson) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.UpdateToCartAsync(requestBodyJson, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnUpdateCart Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
string data = (string)rA.parsedData;
Debug.Log("OnUpdateCart Success with response: " + data);
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>(data);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnUpdateCart Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateComplete, new UIGenericEventPasser("Current Cart Fetched/Updated Successfully!", false, false));
//EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUpdateCart Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnUpdateCart(requestBodyJson);
} else {
StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnUpdateCart Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnUpdateCart Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_LoggedInUserCartUpdateComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnApplyCouponToCart(ApplyCouponRequestBody requestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.ApplyCouponToCartAsync(requestBody, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnApplyCouponToCart Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnApplyCouponToCart Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartComplete, new UIGenericEventPasser("Current Cart Fetched/Updated Successfully!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnApplyCouponToCart Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnApplyCouponToCart(requestBody);
} else {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnApplyCouponToCart Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnApplyCouponToCart Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_ApplyCouponToCartComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnCreateOrder(CreateOrderRequestBody requestBody) {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.CreateOrderAsync(requestBody, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
Debug.Log(string.Format("<color=blue>OnCreateOrder Actual:</color> {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
DefaultWebResponseData<DefaultWebResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<DefaultWebResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnCreateOrder Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserComplete, new UIGenericEventPasser("Order Created Successfully!", false, false));
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateOrder Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnCreateOrder(requestBody);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnCreateOrder Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnCreateOrder Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserProgress, new UIGenericEventPasser("Creating your order...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_OrderCreateForLoggedInUserComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnGetAllOrders(DBGetAllOrdersEventPasser eventPasser) {
APIController.instance.OnPingServer(sR => {
if(sR) {
if(!string.IsNullOrEmpty(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid))) {
APIController.instance.GetAllOrdersAsync(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), eventPasser.paginationRequired, eventPasser.lastEvalutedKeyOrderNo, rA => {
if(rA.meta.isSuccess) {
string test = (string)rA.parsedData;
Debug.Log(string.Format("<color=blue>OnGetAllOrders Actual:</color> {0}, StatusCode: {1}", test, rA.statusCode));
try {
DefaultWebResponseData<GetAllOrdersResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<GetAllOrdersResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnGetAllOrders Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
userOrdersSO.CheckAndUpdateOrders(ConvertAllOrders(defaultWebResponse.ConvertedBody));
if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.orderNo)) {
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(true, defaultWebResponse.ConvertedBody.LastEvaluatedKey.orderNo));
} else {
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser("All Orders Fetched Successfully!", false, false));
}
} else {
if(defaultWebResponse.statusCode == 400) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAllOrders(eventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOrders Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser(error, true, false));
}
}
} catch(Exception ex2) {
Debug.Log("<color=red>OnGetAllOrders Exception</color> -> " + ex2.Message);
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAllOrders(eventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOrders Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOrders Progress: {0}", pA.progress));
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserProgress, new UIGenericEventPasser("Fetching all orders....", false, false, pA));
});
} else {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAllOrders(eventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
}
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_GetAllOrdersForLoggedInUserComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnGetAllOffers() {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetAllOffersAsync(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<GetAllOffersResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<GetAllOffersResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
var convertedBody = defaultWebResponse.ConvertedBody;
Debug.Log(string.Format("OnGetAllOffers Success: {0}, StatusCode: {1}", JsonUtility.ToJson(convertedBody), rA.statusCode));
if(userOffersSO.info == null) {
userOffersSO.info = new UserOffersInfo();
userOffersSO.info.offers = new List<UserOfferData>();
}
userOffersSO.info.offers = ConvertAllOffers(defaultWebResponse.ConvertedBody);
//if(defaultWebResponse.ConvertedBody.LastEvaluatedKey != null && !string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.LastEvaluatedKey.orderNo)) {
//    EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(true, defaultWebResponse.ConvertedBody.LastEvaluatedKey.orderNo));
//}
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser("All Offers Fetched Successfully!", false, false));
} else {
if(defaultWebResponse.statusCode == 400) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAllOffers();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOffers Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser(error, true, false));
}
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnGetAllOffers();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOffers Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnGetAllOffers Progress: {0}", pA.progress));
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserProgress, new UIGenericEventPasser("Fetching all offers....", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_GetAllOffersForLoggedInUserComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void GetPaypalURLForLoggedInUser() {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetPaypalURL(GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<GetPaypalURLResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<GetPaypalURLResponseBody>>((string)rA.parsedData);
string body = defaultWebResponse.body;
StringBuilder builder = new StringBuilder(body);
builder.Replace(@"\\\", @"\");
defaultWebResponse.body = builder.ToString();
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err == null ? string.Empty : defaultWebResponse.ConvertedBody.err.response.name;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("GetPaypalURLForLoggedInUser Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
if(!string.IsNullOrEmpty(defaultWebResponse.ConvertedBody.url)) {
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser(defaultWebResponse.ConvertedBody.url, false, false));
} else {
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser("Couldn't parse payment URL correctly, please try again!", true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
GetPaypalURLForLoggedInUser();
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPaypalURLForLoggedInUser Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser("Couldn't Fetch Payment URL from Server!", true, false));
}
}
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPaypalURLForLoggedInUser Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}, pA => {
Debug.Log("<color=red>WARNING: </color>" + string.Format("GetPaypalURLForLoggedInUser Progress: {0}", pA.progress));
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserProgress, new UIGenericEventPasser("Fetching paypal url....", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_GetPaypalURLLoggedInUserComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private void OnPaypalConfirmPayment(DBPaypalConfirmEventPasser eventPasser) {
string jsonData = JsonUtility.ToJson(eventPasser);
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.ConfirmPaypalPaymentAsync(jsonData, GetIdTokenOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid), rA => {
if(rA.meta.isSuccess) {
DefaultWebResponseData<ConfirmPaypalPaymentResponseBody> defaultWebResponse = JsonUtility.FromJson<DefaultWebResponseData<ConfirmPaypalPaymentResponseBody>>((string)rA.parsedData);
string error = "Server Error";
try {
error = defaultWebResponse.ConvertedBody.err == null ? string.Empty : defaultWebResponse.ConvertedBody.err.response.name;
} catch(NullReferenceException nex) {
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnPaypalConfirmPayment Success: {0}, StatusCode: {1}", JsonUtility.ToJson(defaultWebResponse.ConvertedBody), rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentComplete, new UIGenericEventPasser(JsonUtility.ToJson(defaultWebResponse.ConvertedBody), false, false));
} else {
if(rA.statusCode == System.Net.HttpStatusCode.Forbidden || rA.statusCode == System.Net.HttpStatusCode.Unauthorized || rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
UserData userData = usersDataSO.GetUserDataOfUser(usersDataSO.info.currentLoggedInUserSettings.uuid);
OnAuthRefresh(userData, result => {
if(result) {
OnPaypalConfirmPayment(eventPasser);
} else {
//StatusBarUtility.instance.SetStatus("Unable to refresh Authentication Token!", StatusType.Bug, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentComplete, new UIGenericEventPasser("Unable to refresh Authentication Token!", true, false));
//EventManager.TriggerEvent(EventName.DB_DoSignOut, new CustomEventPasser());
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.AuthenticationScreen));
}
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnPaypalConfirmPayment Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentComplete, new UIGenericEventPasser(error, true, false));
}
}
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnPaypalConfirmPayment Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}, pA => {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnPaypalConfirmPayment Progress: {0}", pA.progress));
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentProgress, new UIGenericEventPasser("Confirming paypal payment...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_ConfirmPaypalPaymentComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private LoggedInUserCartInfo ConvertUserCart(GetCartResponseBody responseBody) {
LoggedInUserCartInfo loggedInUserCartInfo = new LoggedInUserCartInfo {
createdAt = responseBody.createdAt,
updatedAt = responseBody.updatedAt,
cartCurrency = responseBody.cartCurrency,
cartCoupon = responseBody.cartCoupon,
discountAmount = responseBody.discountAmount,
cartFinalPrice = responseBody.cartFinalPrice,
calculatePrice = new CartCalculatePrice {
cartSubtotal = responseBody.calculatePrice.cartSubtotal,
totalShiping = responseBody.calculatePrice.totalShiping,
totaltax = responseBody.calculatePrice.totaltax
}
};
loggedInUserCartInfo.product = new List<CartProduct>();
foreach(var item in responseBody.product) {
CartProduct newProduct = new CartProduct {
id = item.id,
lang_type = item.lang_type,
title = item.title,
quantity = item.quantity,
price = item.price,
size = item.size,
sizeUnit = item.sizeUnit,
product_id = item.product_id,
user_configure_product_id = item.user_configure_product_id,
createdAt = item.createdAt,
updatedAt = item.updatedAt
};
newProduct.files = new List<CartProductFile>();
foreach(var fileItem in item.files) {
CartProductFile cartProductFile = new CartProductFile {
createdAt = fileItem.createdAt,
updatedAt = fileItem.updatedAt,
mediaType = fileItem.mediaType,
mediaFormat = fileItem.mediaFormat,
platformType = fileItem.platformType,
mediaUrl = fileItem.mediaUrl,
featuredType = fileItem.featuredType
};
cartProductFile = userCartSO.CheckAndDownloadFile(cartProductFile);
newProduct.files.Add(cartProductFile);
}
loggedInUserCartInfo.product.Add(newProduct);
}
return loggedInUserCartInfo;
}
private List<UserOrderData> ConvertAllOrders(GetAllOrdersResponseBody responseBody) {
List<UserOrderData> data = new List<UserOrderData>();
foreach(var item in responseBody.Items) {
var order = new UserOrderData {
customerId = item.customerId,
orderNo = item.orderNo,
orderDate = item.orderDate,
orderStatus = item.orderStatus,
orderType = item.orderType,
orderComment = item.orderComment,
copounCode = item.copounCode,
priceCurrency = item.priceCurrency,
orderFinalPrice = item.orderFinalPrice,
orderDiscountAmount = item.orderDiscountAmount,
calculatePrice = new OrderCalculatePrice {
cartSubtotal = item.calculatePrice.cartSubtotal,
totalShiping = item.calculatePrice.totalShiping,
totaltax = item.calculatePrice.totaltax
},
pay = new OrderPay {
mode = item.pay.mode,
paymentId = item.pay.paymentId,
name = item.pay.name,
//accountno = item.pay.accountno,
//expMonth = item.pay.expMonth,
//expYear = item.pay.expYear,
//securitycode = item.pay.securitycode,
//couponcode = item.pay.couponcode,
remember = item.pay.remember
},
ipaddress = item.ipaddress,
deviceId = item.deviceId,
address = new OrderAddress {
billAddress = new OrderBillAddress {
firstName = item.address.billAddress.firstName,
lastName = item.address.billAddress.lastName,
pincode = item.address.billAddress.pincode,
place = item.address.billAddress.place,
street = item.address.billAddress.street
},
shippingAddress = new OrderShippingAddress {
firstName = item.address.shippingAddress.firstName,
lastName = item.address.shippingAddress.lastName,
pincode = item.address.shippingAddress.pincode,
place = item.address.shippingAddress.place,
street = item.address.shippingAddress.street
},
shippingAddressSame = item.address.shippingAddressSame
},
createdAt = item.createdAt,
updatedAt = item.updatedAt
};
order.product = new List<OrderProduct>();
foreach(var productItem in item.product) {
var orderProduct = new OrderProduct {
id = productItem.id,
lang_type = productItem.lang_type,
title = productItem.title,
quantity = productItem.quantity,
price = productItem.price,
user_configure_product_id = productItem.user_configure_product_id,
size = productItem.size,
sizeUnit = productItem.sizeUnit
};
orderProduct.files = new List<OrderProductFile>();
foreach(var fileItem in productItem.files) {
var productFile = new OrderProductFile {
createdAt = fileItem.createdAt,
updatedAt = fileItem.updatedAt,
mediaFormat = fileItem.mediaFormat,
mediaType = fileItem.mediaType,
platformType = fileItem.platformType,
mediaUrl = fileItem.mediaUrl,
featuredType = fileItem.featuredType
};
productFile = userOrdersSO.CheckAndDownloadFile(productFile);
orderProduct.files.Add(productFile);
}
order.product.Add(orderProduct);
}
data.Add(order);
}
return data;
}
private List<UserOfferData> ConvertAllOffers(GetAllOffersResponseBody responseBody) {
List<UserOfferData> data = new List<UserOfferData>();
foreach(var item in responseBody.Items) {
if(item.available == 1 && item.endDate >= DateTime.Now.GetUnixTime()) {
UserOfferData userOfferData = new UserOfferData {
available = item.available,
copoun_code = item.copoun_code,
username = item.username,
discountType = item.discountType,
percentage = item.percentage,
description = item.description,
switchAmount = item.switchAmount,
discountAmount = item.discountAmount,
minimumAmt = item.minimumAmt,
startDate = item.startDate,
endDate = item.endDate,
createAt = item.createAt,
updatedAt = item.updatedAt,
isUsed = item.isUsed
};
userOfferData.files = new List<OfferFileData>();
for(int i = 0; i < item.files.Count; i++) {
OfferFileData offerFile = new OfferFileData(item.files[i].platformType, item.files[i].mediaUrl, item.files[i].mediaFormat, item.files[i].mediaType, item.files[i].featuredType, item.files[i].createdAt, item.files[i].updatedAt);
userOfferData.files.Add(offerFile);
userOffersSO.CheckAndDownloadFile(offerFile);
}
data.Add(userOfferData);
}
}
return data;
}
#endregion
#region IPStack Methods.
private void OnFetchGeolocationAddressFromIP() {
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.GetGeolocationAddressFromIPAsync(rA => {
if(rA.meta.isSuccess) {
IPStackResponseBody defaultWebResponse = JsonUtility.FromJson<IPStackResponseBody>((string)rA.parsedData);
string error = string.Empty;
try {
error = defaultWebResponse.error.info;
} catch(NullReferenceException nex) {
error = "Server Error";
Debug.Log("<color=red>WARNING: </color>" + nex.Message);
}
if(string.IsNullOrEmpty(error)) {
Debug.Log(string.Format("OnFetchGeolocationAddressFromIP Success: {0}, StatusCode: {1}", (string)rA.parsedData, rA.statusCode));
tempDataSO.info.lastGeolocationAddress = ConvertIPStackGeolocationAddress(defaultWebResponse);
EventManager.TriggerEvent(EventName.UI_FetchIPStackGeolocationAddressComplete, new UIGenericEventPasser("Geolocation Fetched successfully!", false, false));
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnFetchGeolocationAddressFromIP Error: {0}, StatusCode: {1}", error, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_FetchIPStackGeolocationAddressComplete, new UIGenericEventPasser(error, true, false));
}
} else {
if(rA.statusCode == System.Net.HttpStatusCode.BadRequest || rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout) {
OnFetchGeolocationAddressFromIP();
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError && (int)rA.statusCode != 0) {
Debug.Log("<color=red>WARNING: </color>" + string.Format("OnFetchGeolocationAddressFromIP Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
EventManager.TriggerEvent(EventName.UI_FetchIPStackGeolocationAddressComplete, new UIGenericEventPasser(rA.meta.reason, false, true));
}
}
}, pA => {
Debug.Log(string.Format("OnFetchGeolocationAddressFromIP Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
EventManager.TriggerEvent(EventName.UI_FetchIPStackGeolocationAddressProgress, new UIGenericEventPasser("Sign In Progress...", false, false, pA));
});
} else {
Debug.Log("<color=red>WARNING: </color>" + string.Format("Server Ping UnSucessfull. Please Check your internet connection!"));
EventManager.TriggerEvent(EventName.UI_FetchIPStackGeolocationAddressComplete, new UIGenericEventPasser("Server Ping UnSucessfull. Please Check your internet connection!", true, true));
}
});
}
private IPStackGeolocationAddress ConvertIPStackGeolocationAddress(IPStackResponseBody responseBody) {
IPStackGeolocationAddress geolocationAddress = new IPStackGeolocationAddress {
ip = responseBody.ip,
type = responseBody.type,
continent_code = responseBody.continent_code,
continent_name = responseBody.continent_name,
country_code = responseBody.country_code,
country_name = responseBody.country_name,
region_code = responseBody.region_code,
region_name = responseBody.region_name,
city = responseBody.city,
zip = responseBody.zip,
latitude = responseBody.latitude,
longitude = responseBody.longitude,
location = new IPStackLocationData {
geoname_id = responseBody.location.geoname_id,
capital = responseBody.location.capital,
country_flag = responseBody.location.country_flag,
country_flag_emoji = responseBody.location.country_flag_emoji,
country_flag_emoji_unicode = responseBody.location.country_flag_emoji_unicode,
calling_code = responseBody.location.calling_code,
is_eu = responseBody.location.is_eu
}
};
geolocationAddress.location.languages = new List<IPStackLanguageData>();
foreach(var item in responseBody.location.languages) {
geolocationAddress.location.languages.Add(new IPStackLanguageData {
code = item.code,
name = item.name,
native = item.native
});
}
return geolocationAddress;
}
#endregion
}
}

4. Files Download Manager

For downloading and managing any file for this game this class is used. It uses C-Sharp’s GUID system to create a unique identifier for each file that have either being marked to download, is in-progress, have been downloaded or was downloaded before but delete now.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Hotchform.Game.Triumph.API;
using Hotchform.Game.Triumph.API.DataModels;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Scriptables;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       03/08/2018 15:01
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
namespace Hotchform.Game.Triumph.Managers {
public class FilesDownloaderManager : MonoBehaviour {
#region Public Variables.
public static FilesDownloaderManager instance = null;
public FilesDownloaderSO filesDownloaderSO;
public static string BaseDownloadFolderName = "CustomDownloads";
public static string ImageDownloadFolderName = "Images";
public static string VideoDownloadFolderName = "Videos";
public static string AudioDownloadFolderName = "Audios";
public static string PackageDownloadFolderName = "Packages";
public static string AssetDownloadFolderName = "Assets";
public static string AssetBundleDownloadFolderName = "AssetBundles";
public static string RawMeshDownloadFolderName = "RawMeshes";
public static string TextDownloadFolderName = "TextFiles";
public static string JsonDownloadFolderName = "JsonFiles";
#endregion
#region Private Variables.
private string _lastPersistanceDataPath;
#endregion
#region Unity Methods.
//Awake is always called before any Start functions
void Awake() {
//Check if instance already exists
if(instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if(instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a FilesDownloaderManager.
Destroy(gameObject);
}
private void Start() {
if(string.IsNullOrEmpty(_lastPersistanceDataPath))
_lastPersistanceDataPath = Application.persistentDataPath;
if(Application.persistentDataPath != _lastPersistanceDataPath) {
Debug.Log(string.Format("Last PersistentDataPath: {0}, Current PersistentDataPath: {1}", _lastPersistanceDataPath, Application.persistentDataPath));
foreach(var item in filesDownloaderSO.info.files) {
item.localURI = item.localURI.Replace(_lastPersistanceDataPath, Application.persistentDataPath);
}
}
_lastPersistanceDataPath = Application.persistentDataPath;
CheckAllDirectories();
}
#endregion
#region Custom Methods.
private void CheckAllDirectories() {
foreach(FileType fileType in Enum.GetValues(typeof(FileType))) {
switch(fileType) {
case FileType.Image:
CheckAndCreateFolder(fileType, ImageDownloadFolderName);
break;
case FileType.Video:
CheckAndCreateFolder(fileType, VideoDownloadFolderName);
break;
case FileType.Audio:
CheckAndCreateFolder(fileType, AudioDownloadFolderName);
break;
case FileType.Package:
CheckAndCreateFolder(fileType, PackageDownloadFolderName);
break;
case FileType.Asset:
CheckAndCreateFolder(fileType, AssetDownloadFolderName);
break;
case FileType.AssetBundle:
CheckAndCreateFolder(fileType, AssetBundleDownloadFolderName);
break;
case FileType.RawMesh:
CheckAndCreateFolder(fileType, RawMeshDownloadFolderName);
break;
case FileType.Text:
CheckAndCreateFolder(fileType, TextDownloadFolderName);
break;
case FileType.Json:
CheckAndCreateFolder(fileType, JsonDownloadFolderName);
break;
default:
break;
}
}
}
private string CheckAndCreateFolder(FileType fileType, string folderName) {
string directoryPath;
if(fileType == FileType.Asset || fileType == FileType.AssetBundle || fileType == FileType.Package || fileType == FileType.RawMesh) {
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, folderName));
} else {
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, folderName));
}
if(!Directory.Exists(directoryPath)) {
Directory.CreateDirectory(directoryPath);
}
return directoryPath;
}
private string GetFilePath(FileType fileType, string fileNameWithExtension) {
string directoryPath;
string fullPath;
switch(fileType) {
case FileType.Image:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, ImageDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Video:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, VideoDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Audio:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, AudioDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Package:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, PackageDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Asset:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, AssetDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.AssetBundle:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, AssetBundleDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.RawMesh:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, RawMeshDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Text:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, TextDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
case FileType.Json:
directoryPath = Path.Combine(Application.persistentDataPath, Path.Combine(BaseDownloadFolderName, JsonDownloadFolderName));
fullPath = Path.Combine(directoryPath, fileNameWithExtension);
break;
default:
fullPath = string.Empty;
break;
}
return fullPath;
}
public void CheckAndDownloadAsync(FileType fileType, string fileExtension, string remoteURI, Action<FileData> fileCreationAction, Action<FileData> fileAction, Action<FileData> progressAction = null, bool isSilent = false) {
if(!CheckIfDownloaded(remoteURI, out FileData newFileData)) {
if(newFileData == null) {
newFileData = new FileData(fileType, fileExtension, remoteURI);
filesDownloaderSO.info.files.Add(newFileData);
}
if(newFileData.HasDownloaded && File.Exists(newFileData.localURI)) {
fileAction?.Invoke(newFileData);
} else {
DownloadFileAsync(newFileData, cA => fileCreationAction?.Invoke(cA), fA => fileAction?.Invoke(fA), pA => progressAction?.Invoke(pA), isSilent);
}
} else {
//fileAction?.Invoke(newFileData);
DownloadFileAsync(newFileData, cA => fileCreationAction?.Invoke(cA), fA => fileAction?.Invoke(fA), pA => progressAction?.Invoke(pA), isSilent);
}
}
public void CheckAndDownloadAsync(FileType fileType, string fileExtension, string remoteURI, IFileData fileData, Action<FileData> fileCreationAction, Action<FileData> fileAction, Action<FileData> progressAction = null, bool isSilent = false) {
if(!CheckIfDownloaded(remoteURI, out FileData newFileData)) {
if(newFileData == null) {
newFileData = new FileData(fileType, fileExtension, remoteURI);
filesDownloaderSO.info.files.Add(newFileData);
}
fileData.UpdateFileData(newFileData.uuid);
//filesDownloaderSO.GetFileData(newFileData.uuid).HasDownloaded = filesDownloaderSO.GetFileData(newFileData.uuid).isDownloaded;
DownloadFileAsync(newFileData, cA => fileCreationAction?.Invoke(cA), fA => {
fileAction?.Invoke(fA);
}, pA => progressAction?.Invoke(pA), isSilent);
} else {
fileData.UpdateFileData(newFileData.uuid);
//filesDownloaderSO.GetFileData(newFileData.uuid).HasDownloaded = filesDownloaderSO.GetFileData(newFileData.uuid).isDownloaded;
fileCreationAction?.Invoke(newFileData);
fileAction?.Invoke(newFileData);
}
}
public void DeleteFileDataCompletely(string uuid, IFileData source) {
if(filesDownloaderSO.info.files.Any(f => f.uuid == uuid)) {
FileData fileData = filesDownloaderSO.info.files.Find(f => f.uuid == uuid);
//Deleting local file.
if(!string.IsNullOrEmpty(fileData.localURI) && File.Exists(fileData.localURI))
File.Delete(fileData.localURI);
filesDownloaderSO.info.files.Remove(fileData);
source.UpdateFileData(string.Empty);
}
}
public void UpdateFileData(string uuid, string newRemoteURI, Action<FileData> fileAction = null) {
if(filesDownloaderSO.info.files.Any(f => f.uuid == uuid)) {
FileData fileData = filesDownloaderSO.info.files.Find(f => f.uuid == uuid);
fileData.remoteURI = newRemoteURI;
//Deleting local file.
if(!string.IsNullOrEmpty(fileData.localURI) && File.Exists(fileData.localURI))
File.Delete(fileData.localURI);
fileData.isDownloaded = false;
fileData.isFailure = false;
fileData.progress = 0f;
fileData.totalContentDownloaded = 0;
fileData.contentLength = 0;
//DownloadFileAsync(fileData, null, fA => fileAction?.Invoke(fA));
}
}
private void DownloadFileAsync(FileData fileData, Action<FileData> fileCreationAction, Action<FileData> fileAction, Action<FileData> progressAction = null, bool topPriority = false, bool isSilent = false) {
fileCreationAction?.Invoke(fileData);
APIController.instance.OnPingServer(sR => {
if(sR) {
APIController.instance.DownloadGenericFile(topPriority, fileData.fileType, fileData.remoteURI, rA => {
if(rA.meta.isSuccess) {
if(!isSilent)
Debug.Log("CheckAndDownloadAsync File Download Started for RemoteURI: " + fileData.remoteURI);
//fileAction(fileData);
string fileNameWithExtension;
if(string.IsNullOrEmpty(fileData.fileExtension))
fileNameWithExtension = fileData.uuid;
else
fileNameWithExtension = fileData.uuid + "." + fileData.fileExtension;
string fullFilePath = GetFilePath(fileData.fileType, fileNameWithExtension);
fileData.localURI = fullFilePath;
if(rA.parsedData == null) {
fileData.progress = 0f;
fileData.HasDownloaded = false;
fileData.isDownloaded = false;
fileData.isFailure = true;
fileData.errorMessage = "Parsed Data is Null";
} else {
WriteAllBytes(fileData.localURI, (byte[])rA.parsedData);
//File.WriteAllBytes(fullFilePath, (byte[])rA.parsedData);
fileData.progress = 1f;
fileData.HasDownloaded = true;
fileData.isDownloaded = true;
fileData.isFailure = false;
fileData.errorMessage = "File Downloaded Successfully!";
}
fileAction?.Invoke(fileData);
} else {
if(rA.statusCode == System.Net.HttpStatusCode.GatewayTimeout || rA.statusCode == System.Net.HttpStatusCode.InternalServerError || rA.statusCode == System.Net.HttpStatusCode.BadRequest) {
if(fileData.HasDownloaded && File.Exists(fileData.localURI)) {
fileData.progress = 1f;
fileData.HasDownloaded = true;
fileData.isDownloaded = true;
fileData.isFailure = false;
fileData.errorMessage = "File Downloaded Successfully!";
} else {
DownloadFileAsync(fileData, fileCreationAction, fileAction, progressAction, isSilent);
fileData.progress = 0f;
fileData.isDownloaded = false;
fileData.isFailure = true;
fileData.errorMessage = rA.meta.reason;
fileData.contentLength = 0;
fileData.totalContentDownloaded = 0;
fileData.errorMessage = "Starting Download Again!";
}
} else if(rA.statusCode != System.Net.HttpStatusCode.InternalServerError || (int)rA.statusCode != 0) {
if(!isSilent)
Debug.LogWarning(string.Format("CheckAndDownloadAsync Failure: {0}, StatusCode: {1}", rA.meta.reason, rA.statusCode));
fileData.progress = 0f;
fileData.isDownloaded = false;
fileData.isFailure = true;
fileData.errorMessage = rA.meta.reason;
fileData.contentLength = 0;
fileData.totalContentDownloaded = 0;
fileAction?.Invoke(fileData);
}
}
}, pA => {
//if(!isSilent)
//	Debug.Log(string.Format("CheckAndDownloadAsync Progress: {0}, ContentLength: {1}, TotalContentCompleted: {2}", pA.progress, pA.contentLength, pA.totalContentCompleted));
if(fileData.isFailure) {
fileData.isDownloaded = false;
fileData.progress = 0f;
fileData.isFailure = true;
fileData.contentLength = 0;
fileData.totalContentDownloaded = 0;
progressAction?.Invoke(fileData);
} else {
fileData.progress = pA.progress;
fileData.isFailure = false;
fileData.contentLength = pA.contentLength;
fileData.totalContentDownloaded = pA.totalContentCompleted;
progressAction?.Invoke(fileData);
}
});
//}
} else {
string error = "CheckAndDownloadAsync Error: Server Ping UnSucessfull. Please Check your internet connection!";
if(!isSilent)
Debug.LogWarning(error);
StatusBarUtility.instance.SetStatus("Server Ping UnSucessfull. Please Check your internet connection!", StatusType.Warning, StatusDelay.STAY);
fileData.progress = 0f;
fileData.isDownloaded = false;
fileData.isFailure = true;
fileData.errorMessage = error;
fileAction?.Invoke(fileData);
}
});
}
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
private void WriteAllBytes(string fileName, byte[] bytes, int chunkSizeDesired = 4096) {
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try {
var stream = new FileStream(fileName, FileMode.OpenOrCreate);
var writer = new BinaryWriter(stream);
var bytesLeft = bytes.Length;
var bytesWritten = 0;
while(bytesLeft > 0) {
var chunkSize = Mathf.Min(chunkSizeDesired, bytesLeft);
writer.Write(bytes, bytesWritten, chunkSize);
bytesWritten += chunkSize;
bytesLeft -= chunkSize;
}
writer.Close();
stream.Close();
writer.Dispose();
stream.Dispose();
} finally {
// Release lock
_readWriteLock.ExitWriteLock();
}
}
private bool CheckIfDownloaded(string remoteURI, out FileData fileData) {
bool retValue = filesDownloaderSO.info.files.Any(f => f.remoteURI == remoteURI);
if(retValue) {
fileData = filesDownloaderSO.info.files.Find(f => f.remoteURI == remoteURI);
} else {
fileData = null;
}
return retValue;
}
#endregion
}
}

5. Save And Load Manager

Each Scriptable Object’s data is stored in a binary encrypted custom extension “.sav” file. This class manages their existence and real-time save and load management system. Due to this methodology it is very easy to access data while it is being either saved or loaded by different entities at the same time.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.AccessControl;
using System.Threading;
using System.Threading.Tasks;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Scriptables;
using Hotchform.Game.Triumph.Utilities;
using UnityEditor;
using UnityEngine;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       28/08/2018 12:36
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
namespace Hotchform.Game.Triumph.Managers {
public class SaveAndLoadManager : MonoBehaviour {
#region Public Variables.
public static SaveAndLoadManager instance = null;
#endregion
#region Private Variables.
private static readonly string baseSaveFolderName = "DataSaveFiles";
private static readonly string mainGameSettingsDataFileName = Path.Combine(baseSaveFolderName, "mainGameSettingsInfo.sav");
private static readonly string languageDataSaveFileName = Path.Combine(baseSaveFolderName, "languageDataInfo.sav");
private static readonly string filesDownloaderSaveFileName = Path.Combine(baseSaveFolderName, "filesDownloaderInfo.sav");
private static readonly string usersDataSaveFileName = Path.Combine(baseSaveFolderName, "usersDataInfo.sav");
private static readonly string tempDataSaveFileName = Path.Combine(baseSaveFolderName, "tempDataInfo.sav");
private static readonly string publicProductsDataSaveFileName = Path.Combine(baseSaveFolderName, "publicProductsDataInfo.sav");
private static readonly string userConfigurableProductDataSaveFileName = Path.Combine(baseSaveFolderName, "userConfigurableProductInfo.sav");
private static readonly string privacyPolicyDataSaveFileName = Path.Combine(baseSaveFolderName, "privacyPolicyDataInfo.sav");
private static readonly string termsAndConditionsDataSaveFileName = Path.Combine(baseSaveFolderName, "termsAndConditionsDataInfo.sav");
private static readonly string userCartDataSaveFileName = Path.Combine(baseSaveFolderName, "userCartDataInfo.sav");
private static readonly string userOffersDataSaveFileName = Path.Combine(baseSaveFolderName, "userOffersDataInfo.sav");
private static readonly string userOrdersDataSaveFileName = Path.Combine(baseSaveFolderName, "userOrdersDataInfo.sav");
private static readonly string scanDataSaveFileName = Path.Combine(baseSaveFolderName, "scanDataInfo.sav");
#endregion
#region Unity Methods.
//Awake is always called before any Start functions
void Awake() {
//Check if instance already exists
if(instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if(instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a DataManager.
Destroy(gameObject);
}
private void OnEnable() {
LoadAllData();
}
private void OnDisable() {
SaveAllData();
}
private void Start() {
LoadAllData();
}
private void OnApplicationQuit() {
foreach(var fileItem in FilesDownloaderManager.instance.filesDownloaderSO.info.files.Where(f => f.isFailure || (f.progress > 0f && f.progress < 1f)).ToList()) {
fileItem.progress = 0f;
fileItem.HasDownloaded = false;
fileItem.isDownloaded = false;
fileItem.isFailure = false;
fileItem.contentLength = 0;
fileItem.totalContentDownloaded = 0;
if(File.Exists(fileItem.localURI)) {
File.Delete(fileItem.localURI);
}
fileItem.localURI = string.Empty;
}
SaveAllData();
Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
foreach(var item in ImageUtils.instantiatedTexturesToDeletePostScene) {
//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
Destroy(item);
//DeleteInstantiatedTexture2D(item);
}
foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
Destroy(item);
//DeleteInstantiatedTexture2D(item);
}
Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeletePostScene.Count + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
ImageUtils.instantiatedTexturesToDeletePostScene = new HashSet<Texture2D>();
ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
foreach(var item in ImageUtils.instantiatedSpritesToDeletePostScene) {
//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
Destroy(item);
//DeleteInstantiatedTexture2D(item);
}
foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
Destroy(item);
//DeleteInstantiatedTexture2D(item);
}
Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeletePostScene.Count + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
ImageUtils.instantiatedSpritesToDeletePostScene = new HashSet<Sprite>();
ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
}
#endregion
#region Save and Load Methods.
private static T LoadData<T>(string fileName) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + fileName, FileMode.Open);
string savedString = (string)bf.Deserialize(file);
T test = JsonUtility.FromJson<T>(savedString);
file.Close();
return test;
}
private static void SaveData<T>(T data, string fileName) {
var directoryToCheck = Application.persistentDataPath + "/" + baseSaveFolderName;
if(!Directory.Exists(directoryToCheck))
Directory.CreateDirectory(directoryToCheck);
BinaryFormatter bf = new BinaryFormatter();
//Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
FileStream file = File.Create(Application.persistentDataPath + "/" + fileName); //you can call it anything you want
bf.Serialize(file, JsonUtility.ToJson(data));
file.Close();
}
private static T CheckAndLoadData<T>(string fileName, T defaultData) {
if(File.Exists(Application.persistentDataPath + "/" + fileName)) {
return LoadData<T>(fileName);
} else {
SaveData<T>(defaultData, fileName);
return defaultData;
}
}
#endregion
#region Custom Methods.
public void SaveAllData() {
// MainGameSettingsInfo Save.
SaveData(GameSettingsManager.instance.gameSettingsSO.info, mainGameSettingsDataFileName);
// LanguageDataInfo Save.
SaveData(LanguageManager.instance.languageDataSO.info, languageDataSaveFileName);
// FilesDownloaderInfo Save.
SaveData(FilesDownloaderManager.instance.filesDownloaderSO.info, filesDownloaderSaveFileName);
// UsersDataInfo Save.
SaveData(DataManager.instance.usersDataSO.info, usersDataSaveFileName);
// TempDataInfo Save.
SaveData(DataManager.instance.tempDataSO.info, tempDataSaveFileName);
// PublicProductsInfo Save.
SaveData(DataManager.instance.publicProductsSO.info, publicProductsDataSaveFileName);
// UserConfigurableInfo Save.
SaveData(DataManager.instance.userConfigurableProductSO.info, userConfigurableProductDataSaveFileName);
// PrivacyPolicyInfo Save.
SaveData(DataManager.instance.privacyPolicyDataSO.info, privacyPolicyDataSaveFileName);
// TermsAndConditionsInfo Save.
SaveData(DataManager.instance.termsAndConditionDataSO.info, termsAndConditionsDataSaveFileName);
// UserCartInfo Save.
SaveData(DataManager.instance.userCartSO.info, userCartDataSaveFileName);
// UserOffersInfo Save.
SaveData(DataManager.instance.userOffersSO.info, userOffersDataSaveFileName);
// UserOrdersInfo Save.
SaveData(DataManager.instance.userOrdersSO.info, userOrdersDataSaveFileName);
// ScanDataInfo Save.
SaveData(DataManager.instance.scanDataSO.info, scanDataSaveFileName);
}
public void LoadAllData() {
// MainGameSettingsInfo Load.
GameSettingsManager.instance.gameSettingsSO.info = CheckAndLoadData(mainGameSettingsDataFileName, new MainGameSettingsInfo());
// LanguageDataInfo Load.
LanguageManager.instance.languageDataSO.info = CheckAndLoadData(languageDataSaveFileName, new LanguageInfo());
// FilesDownloaderInfo Load.
FilesDownloaderManager.instance.filesDownloaderSO.info = CheckAndLoadData(filesDownloaderSaveFileName, new FilesDownloaderInfo());
// UserDataInfo Load.
DataManager.instance.usersDataSO.info = CheckAndLoadData(usersDataSaveFileName, new UsersDataSOInfo());
// TempDataInfo Load.
DataManager.instance.tempDataSO.info = CheckAndLoadData(tempDataSaveFileName, new TempDataSOInfo());
// PublicProductsInfo Load.
DataManager.instance.publicProductsSO.info = CheckAndLoadData(publicProductsDataSaveFileName, new PublicProductsInfo());
// UserConfigurableInfo Load.
DataManager.instance.userConfigurableProductSO.info = CheckAndLoadData(userConfigurableProductDataSaveFileName, new UserConfigurableProductInfo());
// PrivacyPolicyInfo Load.
DataManager.instance.privacyPolicyDataSO.info = CheckAndLoadData(privacyPolicyDataSaveFileName, new PrivacyPolicyInfo());
// TemsAndConditionsInfo Load.
DataManager.instance.termsAndConditionDataSO.info = CheckAndLoadData(termsAndConditionsDataSaveFileName, new TermsAndConditionInfo());
// UserCartInfo Load.
DataManager.instance.userCartSO.info = CheckAndLoadData(userCartDataSaveFileName, new LoggedInUserCartInfo());
// UserOffersInfo Load.
DataManager.instance.userOffersSO.info = CheckAndLoadData(userOffersDataSaveFileName, new UserOffersInfo());
// UserOrdersInfo Load.
DataManager.instance.userOrdersSO.info = CheckAndLoadData(userOrdersDataSaveFileName, new UserOrdersInfo());
// ScanDataInfo Load.
DataManager.instance.scanDataSO.info = CheckAndLoadData(scanDataSaveFileName, new ScanInfo());
}
#if UNITY_EDITOR
[MenuItem("Hotchform/Triumph/Tools/Clear All Saved Files")]
private static void ClearAllSavedFiles() {
var mainGameSettingsDataSaveFilePath = Path.Combine(Application.persistentDataPath, mainGameSettingsDataFileName);
if(File.Exists(mainGameSettingsDataSaveFilePath))
File.Delete(mainGameSettingsDataSaveFilePath);
var languageDataSaveFilePath = Path.Combine(Application.persistentDataPath, languageDataSaveFileName);
if(File.Exists(languageDataSaveFilePath))
File.Delete(languageDataSaveFilePath);
var filesDataSaveFilePath = Path.Combine(Application.persistentDataPath, filesDownloaderSaveFileName);
if(File.Exists(filesDataSaveFilePath))
File.Delete(filesDataSaveFilePath);
var usersDataSaveFilePath = Path.Combine(Application.persistentDataPath, usersDataSaveFileName);
if(File.Exists(usersDataSaveFilePath))
File.Delete(usersDataSaveFilePath);
var tempDataSaveFilePath = Path.Combine(Application.persistentDataPath, tempDataSaveFileName);
if(File.Exists(tempDataSaveFilePath))
File.Delete(tempDataSaveFilePath);
var publicProductsDataSaveFilePath = Path.Combine(Application.persistentDataPath, publicProductsDataSaveFileName);
if(File.Exists(publicProductsDataSaveFilePath))
File.Delete(publicProductsDataSaveFilePath);
var userConfigurablesDataSaveFilePath = Path.Combine(Application.persistentDataPath, userConfigurableProductDataSaveFileName);
if(File.Exists(userConfigurablesDataSaveFilePath))
File.Delete(userConfigurablesDataSaveFilePath);
var privacyPolicyDataSaveFilePath = Path.Combine(Application.persistentDataPath, privacyPolicyDataSaveFileName);
if(File.Exists(privacyPolicyDataSaveFilePath))
File.Delete(privacyPolicyDataSaveFilePath);
var termsAndConditionsDataSaveFilePath = Path.Combine(Application.persistentDataPath, termsAndConditionsDataSaveFileName);
if(File.Exists(termsAndConditionsDataSaveFilePath))
File.Delete(termsAndConditionsDataSaveFilePath);
var userCartDataSaveFilePath = Path.Combine(Application.persistentDataPath, userCartDataSaveFileName);
if(File.Exists(userCartDataSaveFilePath))
File.Delete(userCartDataSaveFilePath);
var userOffersDataSaveFilePath = Path.Combine(Application.persistentDataPath, userOffersDataSaveFileName);
if(File.Exists(userOffersDataSaveFilePath))
File.Delete(userOffersDataSaveFilePath);
var userOrdersDataSaveFilePath = Path.Combine(Application.persistentDataPath, userOrdersDataSaveFileName);
if(File.Exists(userOrdersDataSaveFilePath))
File.Delete(userOrdersDataSaveFilePath);
var scanDataSaveFilePath = Path.Combine(Application.persistentDataPath, scanDataSaveFileName);
if(File.Exists(scanDataSaveFilePath))
File.Delete(scanDataSaveFilePath);
}
#endif
}
#endregion
}//Code Goes here

6. Scan Game Play Manager

The project started out as a prototype with this module which was ideated to manage the custom “Scan-Tech” for the Photogrammetry module of the project. This “Scan-Tech” is the U.S.P of this product as unlike other photogrammetry based scan applications, this module had automated capturing capability, advanced image processing, multi-threading and psuedo-A.I.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using Code5.Game;
using Fabric.Crashlytics;
using Hotchform.Game.Triumph.Utilities;
using NatCamU.Core;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
/*===============================================================
Product:    #PROJECTNAME#
Developer:  #DEVELOPERNAME#
Company:    #COMPANY#
Date:       #CREATIONDATE#
Copyright:  #COPYRIGHT#
================================================================*/
using Hotchform.Game.Triumph.Utilities.Mono;
using System.Linq;
using System.Security.Cryptography;
namespace Hotchform.Game.Triumph.Managers {
public class ScanGamePlayManager : MonoBehaviour {
#region Public Variables.
[Header("Camera")]
public bool useFrontCamera;
[Header("UI")]
public RawImage rawImage;
public RawImage overlayRawImage;
public AspectRatioFitter aspectFitter;
public AspectRatioFitter overLayAspectFitter;
public UnityEngine.UI.Text flashText;
public Button switchCamButton, flashButton;
public Image flashIco;
public UnityEvent OnCapturingFinished;
#endregion
#region Private Variables.
private int _updateCounter = 0;
//private Texture2D _lastPhoto;
[SerializeField] private UnityEngine.UI.Text _snapCounterText;
[SerializeField] private UnityEngine.UI.Text _gameStateButtonText;
[SerializeField] private UnityEngine.UI.Text _currentDebugText;
[SerializeField] private NewGameState _currentGameState;
[SerializeField] private GameObject _gamePauseButtonObject;
private List<string> _snapshotPaths = new List<string>();
private int _snapshotsCount = 0;
private bool _doSaveIn2X = true;
private float _elapsed = 0f;
private string _snapDirPath;
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
Resources.UnloadUnusedAssets();
Application.runInBackground = true;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
DataManager.instance.scanDataSO.info.buildVersion = "v" + Application.version + "b";
DataManager.instance.scanDataSO.info.timeStamp = string.IsNullOrEmpty(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder.timestamp) ? DateTime.UtcNow.GetUnixTime().ToString() : DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.oldthreeDscanFolder.timestamp;
//Debug.Log("_albumDateTime-> " + _albumDateTime);
_snapDirPath = Application.persistentDataPath;
string albumName = "Snaps_" + DateTime.Now.ToString("ddMMyyyy_HHmmss");
_snapDirPath = Path.Combine(_snapDirPath, "Triumph_Snaps/" + albumName);
string toDeletePath = Path.Combine(Application.persistentDataPath, "Triumph_Snaps");
if(Directory.Exists(toDeletePath))
Directory.Delete(Path.Combine(Application.persistentDataPath, "Triumph_Snaps"), true);
if(!Directory.Exists(_snapDirPath)) {
Directory.CreateDirectory(_snapDirPath);
}
DataManager.instance.scanDataSO.info.rowOneScanDatum.Clear();
DataManager.instance.scanDataSO.info.rowTwoScanDatum.Clear();
//#if UNITY_IOS
//			if(SystemInfo.graphicsDeviceName.Contains("A8")) {
//				GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.minimumCaptureLimit = 2;
//				GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.maximumCaptureLimit = 125;
//				GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.uploadImageResolution = 1;
//			} else {
//				GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.minimumCaptureLimit = 2;
//				GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.maximumCaptureLimit = 125;
//			}
//#endif
_currentGameState = NewGameState.Stopped;
if(Application.isEditor)
useFrontCamera = true;
NatCam.Camera = useFrontCamera ? DeviceCamera.FrontCamera : DeviceCamera.RearCamera;
if(!NatCam.Camera) {
Debug.LogError("Camera is null. Consider using " + (useFrontCamera ? "rear" : "front") + " camera");
return;
}
NatCam.Camera.PreviewResolution = CameraResolution._1280x720;
NatCam.Camera.PhotoResolution = CameraResolution._1920x1080;
NatCam.Play();
NatCam.OnStart += OnStart;
Crashlytics.SetDebugMode(true);
Crashlytics.SetUserName(albumName);
Crashlytics.SetKeyValue("ScanGamePlay Session Start", albumName);
Crashlytics.Log("ScanGamePlay Session Test Log: " + DateTime.Now.ToLongDateString());
//Crashlytics.Crash();
//Crashlytics.ThrowNonFatal();
}
// Update is called once per frame
void Update() {
// Display the preview
rawImage.texture = NatCam.Preview;
if(DataManager.instance.scanDataSO.info.rowOneScanDatum.Count >= GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.maximumCaptureLimit) {
_currentGameState = NewGameState.Finished;
OnGameStateButtonClick();
}
switch(_currentGameState) {
case NewGameState.Stopped:
_gameStateButtonText.text = "Starten!";// "Start";
_gamePauseButtonObject.SetActive(false);
break;
case NewGameState.InProgress:
if(DataManager.instance.scanDataSO.info.rowOneScanDatum.Count < GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.minimumCaptureLimit) {
_gamePauseButtonObject.SetActive(false);
_gameStateButtonText.text = "Kurz anhalten?";// "Pause";
} else {
_gameStateButtonText.text = "Beenden?";// "Finish";
_gamePauseButtonObject.SetActive(true);
}
if(overlayRawImage.gameObject.activeInHierarchy)
gameObject.SetActive(false);
_elapsed += Time.deltaTime;
if(_elapsed >= GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.scanDelayTime) {
_elapsed = _elapsed % GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.scanDelayTime;
_currentDebugText.text = "Sehr gut! Weiter so!";
System.GC.Collect();
Resources.UnloadUnusedAssets();
CapturePhoto();
}
break;
case NewGameState.Paused:
_gamePauseButtonObject.SetActive(false);
_gameStateButtonText.text = "Fortsetzen!";//"Resume";
if(DataManager.instance.scanDataSO.info.rowOneScanDatum.Count > 1) {
overLayAspectFitter.aspectRatio = aspectFitter.aspectRatio;
if(!overlayRawImage.gameObject.activeInHierarchy)
overlayRawImage.gameObject.SetActive(true);
overlayRawImage.texture = ImageUtils.LoadTexture(DataManager.instance.scanDataSO.info.rowOneScanDatum.Last().localURI);
}
break;
case NewGameState.Finished:
_gamePauseButtonObject.SetActive(false);
_gameStateButtonText.text = "Beenden?";// "Finish";
if(overlayRawImage.gameObject.activeInHierarchy)
gameObject.SetActive(false);
//OnFinish();
break;
default:
_gamePauseButtonObject.SetActive(false);
break;
}
}
#endregion
#region NatCam Callback Methods.
private void OnStart() {
// Display the preview
rawImage.texture = NatCam.Preview;
// Scale the panel to match aspect ratios
aspectFitter.aspectRatio = NatCam.Preview.width / (float)NatCam.Preview.height;
// Enable tap to focus and autofocus
NatCam.Camera.FocusMode = FocusMode.TapToFocus | FocusMode.AutoFocus;
// Set flash to auto
NatCam.Camera.FlashMode = FlashMode.Off;
SetFlashIcon();
}
private void OnPhoto(Texture2D photo) {
StartCoroutine(SaveAsync(photo));
}
#endregion
#region UI Methods.
public virtual void CapturePhoto() {
NatCam.CapturePhoto(OnPhoto);
}
public void SwitchCamera() {
// Switch camera
if(NatCam.Camera.IsFrontFacing)
NatCam.Camera = DeviceCamera.RearCamera;
else
NatCam.Camera = DeviceCamera.FrontCamera;
// Set the flash icon
SetFlashIcon();
}
public void ToggleFlashMode() {
// Set the active camera's flash mode
if(NatCam.Camera.IsFlashSupported)
switch(NatCam.Camera.FlashMode) {
case FlashMode.Auto: NatCam.Camera.FlashMode = FlashMode.On; break;
case FlashMode.On: NatCam.Camera.FlashMode = FlashMode.Off; break;
case FlashMode.Off: NatCam.Camera.FlashMode = FlashMode.Auto; break;
}
// Set the flash icon
SetFlashIcon();
}
public void OnGameStateButtonClick() {
switch(_currentGameState) {
case NewGameState.InProgress:
if(DataManager.instance.scanDataSO.info.rowOneScanDatum.Count < GameSettingsManager.instance.gameSettingsSO.info.scanTechSettings.minimumCaptureLimit)
_currentGameState = NewGameState.Paused;
else {
_currentGameState = NewGameState.Finished;
OnCapturingFinished.Invoke();
}
break;
case NewGameState.Paused:
if(overlayRawImage.gameObject.activeInHierarchy)
overlayRawImage.gameObject.SetActive(false);
_currentGameState = NewGameState.InProgress;
break;
case NewGameState.Stopped:
_currentGameState = NewGameState.InProgress;
break;
case NewGameState.Finished:
//_currentGameState = GameState.InProgress;
OnCapturingFinished.Invoke();
break;
default:
break;
}
}
public void OnGamePauseButtonClick() {
_currentGameState = NewGameState.Paused;
}
#endregion
#region Utility Methods.
private void SetFlashIcon() {
// Set the icon
bool supported = NatCam.Camera.IsFlashSupported;
flashIco.color = !supported || NatCam.Camera.FlashMode == FlashMode.Off ? (Color)new Color32(120, 120, 120, 255) : Color.white;
// Set the auto text for flash
flashText.text = supported && NatCam.Camera.FlashMode == FlashMode.Auto ? "A" : "";
}
#endregion
#region Processing Methods.
private IEnumerator SaveAsync(Texture2D photo) {
bool workDone = false;
while(!workDone) {
// Cache the photo
//_lastPhoto = new Texture2D(2, 2);
//_lastPhoto.LoadImage(photo.EncodeToPNG());
//_lastPhoto.Apply();
//yield return null;
if(DataManager.instance.scanDataSO.info.rowOneScanDatum.Count > 1 && File.Exists(DataManager.instance.scanDataSO.info.rowOneScanDatum.Last().localURI)) {
Texture2D _lastTex = ImageUtils.LoadTexture(DataManager.instance.scanDataSO.info.rowOneScanDatum.Last().localURI);
//int res = OrbFeature2DDetection(photo, _lastTex);//BriskDetector(rowOneTex, lastSavedRowOneTex);
//Debug.Log("res: " + res);
float difference = ImageUtils.DifferenceInImages(photo, _lastTex);
//if(res == 0) {
if(difference > 1f) {
//Debug.Log("Snap Discarded!");
yield return null;
Destroy(_lastTex);
Destroy(photo);
yield return null;
_currentDebugText.text = "Fortsetzen von Position der Ueberblendung.";//"Snap Discarded as Features Didn't match with last frame!";
_currentGameState = NewGameState.Paused;
workDone = true;
break;
} else {
//Debug.Log("Snap Accepted!");
yield return null;
Destroy(_lastTex);
workDone = false;
}
}
_updateCounter++;
string rowOneTextFileName = _updateCounter + "_rowOneSnap" + ".png";
string rowTwoTextFileName = 1000 + _updateCounter + "_rowTwoSnap" + ".png";
string rowOneSnapFilePath = Path.Combine(_snapDirPath, rowOneTextFileName);
//Debug.Log("rowOneSnapFilePath: " + rowOneSnapFilePath);
byte[] fileData = photo.EncodeToPNG();
yield return null;
Destroy(photo);
yield return null;
new Thread(() => {
File.WriteAllBytes(rowOneSnapFilePath, fileData);
}).Start();
string[] fileNameSplit = rowOneSnapFilePath.Split('.');
DataManager.instance.scanDataSO.info.rowOneScanDatum.Add(new DataHandlers.Scriptables.ScanData(rowOneSnapFilePath, false, Path.GetFileNameWithoutExtension(rowOneSnapFilePath), fileNameSplit[1], DataHandlers.Scriptables.FileMediaType.Image));
yield return null;
_snapCounterText.text = _updateCounter.ToString();
workDone = true;
}
}
#endregion
#region Application Methods.
private void OnApplicationQuit() {
_currentGameState = NewGameState.Stopped;
}
#endregion
}
public enum NewGameState {
Stopped,
InProgress,
Paused,
Finished
}
}//Code Goes here

Controllers

1. API Controller

This is the web HTTP/S based API controller system used to communicate to and fro between the AWS based API server.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using CI.HttpClient;
using Hotchform.Game.Triumph.API.DataModels;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.Scriptables;
using UnityEngine;
using UnityEngine.Networking;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       31/07/2018 12:25
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using Hotchform.Game.Triumph.Utilities;
using System.Text.RegularExpressions;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace Hotchform.Game.Triumph.API {
public class APIController : MonoBehaviour {
#region Public Variables.
public static APIController instance = null;
#endregion
#region Private Variables.
private HttpClient _normalHttpClient;
private HttpClient _uploadingHttpClient;
private HttpClient _userConfigurableHttpClient;
private HttpClient _topPriorityHttpClient;
private List<Coroutine> _apiCoroutines = new List<Coroutine>();
private List<Coroutine> _uploadScanAPICoroutines = new List<Coroutine>();
#endregion
#region Unity Methods.
//Awake is always called before any Start functions
void Awake() {
//Check if instance already exists
if(instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if(instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a APIController.
Destroy(gameObject);
}
private void Start() {
}
private void OnEnable() {
_normalHttpClient = new HttpClient();
_uploadingHttpClient = new HttpClient();
_userConfigurableHttpClient = new HttpClient();
_topPriorityHttpClient = new HttpClient();
}
private void OnApplicationQuit() {
_normalHttpClient.Abort();
_uploadingHttpClient.Abort();
_userConfigurableHttpClient.Abort();
foreach(var item in _apiCoroutines) {
StopCoroutine(item);
}
_apiCoroutines.Clear();
SaveAndLoadManager.instance.SaveAllData();
}
#endregion
#region HTTP CLIENT Methods.
public void AbortAllHttpClients(bool abortUploadScanAlso = false, Action<bool> completeAction = null) {
_normalHttpClient.Abort();
_uploadingHttpClient.Abort();
//_userConfigurableHttpClient.Abort();
foreach(var item in _apiCoroutines) {
StopCoroutine(item);
}
_apiCoroutines.Clear();
if(abortUploadScanAlso) {
foreach(var item in _uploadScanAPICoroutines) {
StopCoroutine(item);
}
_uploadScanAPICoroutines.Clear();
_topPriorityHttpClient.Abort();
}
SaveAndLoadManager.instance.SaveAllData();
completeAction?.Invoke(true);
}
#endregion
#region Cognito API Methods.
public void SignUpAsync(string email, string password, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint);
UserSignUpRequestBody userSignUpRequestBody = new UserSignUpRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId, email, password);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PUT_STRING, JsonUtility.ToJson(userSignUpRequestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA));
}
public void SignInAsync(string email, string password, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint);
UserSignInRequestBody userSignInRequestBody = new UserSignInRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId, GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, email, password);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(userSignInRequestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA));
}
public void RefreshAsync(string refreshToken, Action<CustomWebResponse> responseAction) {
//UserRefreshRequestBody userRefreshRequestBody = new UserRefreshRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, refreshToken, GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId);
string fullEndpointUrl = string.Format("{0}/{1}?userpool={2}&RefreshToken={3}&clientId={4}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, refreshToken, GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA));
}
public void ForgotPasswordAsync(string username, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint);
UserForgotPasswordRequestBody userForgotPassword = new UserForgotPasswordRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId, username, GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.DELETE_VIA_JSON, JsonUtility.ToJson(userForgotPassword));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA));
}
public void ConfirmForgotPasswordAsync(string username, string newPassword, string confirmationCode, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint);
UserConfirmForgotPasswordRequestBody userConfirmForgotPassword = new UserConfirmForgotPasswordRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId, username, GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, confirmationCode, newPassword);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.DELETE_VIA_JSON, JsonUtility.ToJson(userConfirmForgotPassword));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA));
}
public static UserAuthResult ConvertAuthResults(AuthenticationResultResponse authenticationResult) {
if(string.IsNullOrEmpty(authenticationResult.AccessToken))
throw new ArgumentNullException(nameof(authenticationResult));
return new UserAuthResult(accessToken: authenticationResult.AccessToken,
expiresIn: authenticationResult.ExpiresIn,
tokenType: authenticationResult.TokenType,
refreshToken: authenticationResult.RefreshToken,
idToken: authenticationResult.IdToken);
}
#endregion
#region Account APIs.
public void CreateAccountAsync(DBUserRegisterEventPasser dBRegisterEventPasser, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction, string authToken) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
UserCreateAccountRequestBody createAccountRequestBody = new UserCreateAccountRequestBody();
//createAccountRequestBody.profilePic = null;
createAccountRequestBody.firstName = dBRegisterEventPasser.firstName;
createAccountRequestBody.lastName = dBRegisterEventPasser.lastName;
createAccountRequestBody.address = new UserFullAddressRequestBody();
createAccountRequestBody.address.billAddress = new UserAddressRequestBody();
createAccountRequestBody.address.billAddress.firstName = dBRegisterEventPasser.firstName;
createAccountRequestBody.address.billAddress.lastName = dBRegisterEventPasser.lastName;
createAccountRequestBody.address.billAddress.street = dBRegisterEventPasser.address.street;
createAccountRequestBody.address.billAddress.place = dBRegisterEventPasser.address.place;
createAccountRequestBody.address.billAddress.pincode = dBRegisterEventPasser.address.pincode;
createAccountRequestBody.address.shippingAddress = createAccountRequestBody.address.billAddress;
createAccountRequestBody.address.shippingAddressSame = true;
createAccountRequestBody.pushNotification = new List<UserOffersOrdersPushNotificationRequestBody>();
createAccountRequestBody.pushNotification.Add(new UserOffersOrdersPushNotificationRequestBody(true, true));
createAccountRequestBody.active = true;
createAccountRequestBody.isPublic = true;
createAccountRequestBody.isConfirmed = true;
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PUT_STRING, JsonUtility.ToJson(createAccountRequestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void GetAccountAsync(string authToken, string uuid, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void GetAccountAllAsync(bool paginationRequested, string lastEvaluatedKeyUsername, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl;
if(!string.IsNullOrEmpty(lastEvaluatedKeyUsername) & paginationRequested) {
fullEndpointUrl = string.Format("{0}/{1}?search=all&LastEvaluatedKeyUsername={2}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint, lastEvaluatedKeyUsername);
} else {
fullEndpointUrl = string.Format("{0}/{1}?search=all", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
}
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void DeleteAccountAsync(string authToken, string userPoolId, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
DeleteAccountResponseBody deleteAccountResponseBody = new DeleteAccountResponseBody(userPoolId);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.DELETE_VIA_JSON, JsonUtility.ToJson(deleteAccountResponseBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void UploadUserProfileAsync(bool updateProfilePic, UserProfileRequestBody requestBody, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction, string authToken) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
if(updateProfilePic)
requestBody = (UserProfileRequestBodyWithPic)requestBody;
else
requestBody = (UserProfileRequestBodyWithoutPic)requestBody;
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PUT_STRING, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
#endregion
#region Server Utility Methods.
public void OnPingServer(Action<bool> successResponse) {
//PingServerAsync(rA => {
//	successResponse(rA.meta.isSuccess);
//});
successResponse?.Invoke(true);
//StartCoroutine(PingServerAsync(sR => successResponse?.Invoke(!sR)));
}
private void PingServerAsync(Action<CustomWebResponse> responseAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PATCH);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA));
}
private IEnumerator PingServerAsync(Action<bool> successResponse) {
UnityWebRequest unityWebRequest = UnityWebRequest.Get(string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cognitoAuthEndpoint));
unityWebRequest.SetRequestHeader("X-HTTP-Method-Override", "OPTIONS");
yield return unityWebRequest.SendWebRequest();
successResponse?.Invoke(unityWebRequest.isHttpError || unityWebRequest.isNetworkError);
}
#endregion
#region File Manager APIs.
public void DownloadGenericFile(bool topPriority, FileType fileType, string remoteURI, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(fileType == FileType.Asset || fileType == FileType.AssetBundle || fileType == FileType.Package || fileType == FileType.RawMesh) {
// if(!topPriority)
// 	_apiCoroutines.Add(StartCoroutine(DownloadFileWithWWW(remoteURI, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA))));
// else
// 	_uploadScanAPICoroutines.Add(StartCoroutine(DownloadFileWithWWW(remoteURI, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA))));
} else {
CustomWebRequest customWebRequest = new CustomWebRequest(remoteURI, HttpMethod.GET_BYTEARRAY);
//if(!topPriority)
//	customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA));
//else
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA));
}
}
public void DownloadAssetBundleFile(FileType fileType, string remoteURI, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
//StartCoroutine(AssetBundleUtils.downloadAssetBundle(remoteURI, 1, rA => responseAction(rA)));
_apiCoroutines.Add(StartCoroutine(DownloadFileWithWWW(remoteURI, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA))));
}
IEnumerator DownloadFileWithWWW(string remoteURI, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
WWW fileWWW = new WWW(remoteURI);
CustomWebResponse customWebResponse = new CustomWebResponse();
customWebResponse.meta = new CustomWebRequestMeta();
CustomWebResponseProgress customWebResponseProgress = new CustomWebResponseProgress();
StartCoroutine(ShowProgress(fileWWW, customWebResponseProgress, progressAction));
yield return fileWWW;
if(fileWWW.error != null || !string.IsNullOrEmpty(fileWWW.error)) {
customWebResponse.meta.reason = fileWWW.error;
customWebResponse.meta.isSuccess = false;
customWebResponse.statusCode = HttpStatusCode.SeeOther;
responseAction?.Invoke(customWebResponse);
} else {
customWebResponse.meta.isSuccess = true;
customWebResponse.parsedData = fileWWW.bytes;
responseAction?.Invoke(customWebResponse);
customWebResponseProgress.progress = fileWWW.progress;
customWebResponseProgress.totalContentCompleted = fileWWW.bytesDownloaded;
progressAction?.Invoke(customWebResponseProgress);
}
}
private IEnumerator ShowProgress(WWW www, CustomWebResponseProgress customWebResponseProgress, Action<CustomWebResponseProgress> progressAction) {
while(!www.isDone) {
customWebResponseProgress.progress = www.progress;
customWebResponseProgress.totalContentCompleted = www.bytesDownloaded;
progressAction?.Invoke(customWebResponseProgress);
yield return new WaitForSeconds(.1f);
}
}
#endregion
#region Language APIs.
public void LanguageDataAsync(Action<CustomWebResponse> responseAction) {
//UserRefreshRequestBody userRefreshRequestBody = new UserRefreshRequestBody(GameSettingsManager.instance.gameSettingsSO.baseSettings.userPool, refreshToken, GameSettingsManager.instance.gameSettingsSO.baseSettings.clientId);
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.languageEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA));
}
#endregion
#region PublicProducts APIs.
public void GetPublicProductsInfo(string langCode, string productType, string lastEvaluatedKeyId, string productId, Action<CustomWebResponse> responseAction) {
string fullEndpointUrl;
if(string.IsNullOrEmpty(lastEvaluatedKeyId) && string.IsNullOrEmpty(productId)) {
fullEndpointUrl = string.Format("{0}/{1}?lang={2}&category={3}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.publicProductsEndpoint, langCode, productType);
} else if(string.IsNullOrEmpty(lastEvaluatedKeyId) & !string.IsNullOrEmpty(productId)) {
fullEndpointUrl = string.Format("{0}/{1}?lang={2}&category={3}&id={4}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.publicProductsEndpoint, langCode, productType, productId);
} else if(!string.IsNullOrEmpty(lastEvaluatedKeyId) & string.IsNullOrEmpty(productId)) {
fullEndpointUrl = string.Format("{0}/{1}?lang={2}&category={3}&lastEvaluatedKeyID={4}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.publicProductsEndpoint, langCode, productType, lastEvaluatedKeyId);
} else {
fullEndpointUrl = string.Format("{0}/{1}?lang={2}&category={3}&lastEvaluatedKeyID={4}&id={5}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.publicProductsEndpoint, langCode, productType, lastEvaluatedKeyId, productId);
}
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA));
}
#endregion
#region UserConfigurable APIs
public void GetAllUserConfigurableProductsAsync(string authToken, string lastEvaluatedProductId, long updatedAt, Action<CustomWebResponse> responseAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl;
if(!string.IsNullOrEmpty(lastEvaluatedProductId)) {
fullEndpointUrl = string.Format("{0}/{1}?lastEvaluatedProductId={2}&updatedAt={3}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userProductEndpoint, lastEvaluatedProductId, updatedAt.ToString());
} else {
fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userProductEndpoint);
}
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_userConfigurableHttpClient, rA => responseAction(rA), null, authToken);
}
}
public void CreateUserConfigurableAsync(DBLastConfigurableEventPasser dBLastConfigurableEventPasser, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction, string authToken) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userProductEndpoint);
CreateUserConfigurableRequestBody createUserConfigurableRequestBody = new CreateUserConfigurableRequestBody();
createUserConfigurableRequestBody.address = new AddressBody(dBLastConfigurableEventPasser.address.street, dBLastConfigurableEventPasser.address.place, dBLastConfigurableEventPasser.address.pincode, new GpsLocationBody(dBLastConfigurableEventPasser.latitude, dBLastConfigurableEventPasser.longitude));
createUserConfigurableRequestBody.dateAndTime = new DateAndTimeBody(dBLastConfigurableEventPasser.startDate, dBLastConfigurableEventPasser.endDate);
createUserConfigurableRequestBody.people = new List<string>(dBLastConfigurableEventPasser.selectedUserEmails);
createUserConfigurableRequestBody.productType = dBLastConfigurableEventPasser.modelType;
createUserConfigurableRequestBody.engraving = dBLastConfigurableEventPasser.engraving;
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(createUserConfigurableRequestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void UpdateUserConfigurableAsync(UpdateUserConfigurableRequestBody requestBody, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction, string authToken) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userProductEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PUT_STRING, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void DeleteUserConfigurableAsync(string authToken, string productId, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.userProductEndpoint);
DeleteUserConfigurableRequestBody deleteUserConfigurableRequestBody = new DeleteUserConfigurableRequestBody(productId);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.DELETE_VIA_JSON, JsonUtility.ToJson(deleteUserConfigurableRequestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
//private IEnumerator Test(UnityWebRequest unityWebRequest, Action<CustomWebResponse> responseAction) {
//    yield return unityWebRequest.SendWebRequest();
//    CustomWebResponse customWebResponse = new CustomWebResponse();
//    customWebResponse.parsedData = unityWebRequest.downloadHandler.text;
//    customWebResponse.statusCode = (HttpStatusCode)unityWebRequest.responseCode;
//    if(string.IsNullOrEmpty(unityWebRequest.error)) {
//        customWebResponse.meta = new CustomWebRequestMeta(unityWebRequest.error, false);
//    } else {
//        customWebResponse.meta = new CustomWebRequestMeta(unityWebRequest.error, true);
//    }
//    Debug.Log(customWebResponse);
//    responseAction?.Invoke(customWebResponse);
//}
public void AddAccountViaUserConfigurableAsync(string fullName, string emailAddress, Action<CustomWebResponse> responseAction, string authToken) {
if(!string.IsNullOrEmpty(authToken)) {
SendInvitationRequestBody sendInvitationRequestBody = new SendInvitationRequestBody(emailAddress, fullName);
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.accountEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(sendInvitationRequestBody));
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), null, authToken);
}
}
public void SendEmailOnScanUploadCompleteAsync(OnScanCompleteEmailRequestBody requestBody, Action<CustomWebResponse> responseAction) {
string fullEndpointUrl = string.Format("{0}", GameSettingsManager.instance.gameSettingsSO.baseSettings.sendPublicEmailEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), null);
}
#endregion
#region Cart & Order APIs
public void GetLoggedInUserCartAsync(string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
if(!string.IsNullOrEmpty(authToken)) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cartEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
}
public void AddToCartNormalAsync(AddToCartRequestBody requestBody, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cartEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void AddToCartWithUserConfigurableAsync(AddToCartWithConfigurableRequestBody requestBody, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cartEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void UpdateToCartAsync(string requestBodyJson, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cartEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PUT_STRING, requestBodyJson);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void ApplyCouponToCartAsync(ApplyCouponRequestBody requestBody, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.cartEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.PATCH, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void CreateOrderAsync(CreateOrderRequestBody requestBody, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.ordersEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(requestBody));
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void GetAllOrdersAsync(string authToken, bool paginationRequired, string lastEvaluatedOrderNo, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.ordersEndpoint);
if(paginationRequired && !string.IsNullOrEmpty(lastEvaluatedOrderNo))
fullEndpointUrl = string.Format("{0}/{1}?lastEvaluatedOrderId={2}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.ordersEndpoint, lastEvaluatedOrderNo);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void GetAllOffersAsync(string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.offersEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void GetPaypalURL(string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.paypalEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
//StartCoroutine(GetPaypalURl(authToken, rA => responseAction?.Invoke(rA), pA => progressAction?.Invoke(pA)));
}
private IEnumerator GetPaypalURl(string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.paypalEndpoint);
UnityWebRequest unityWebRequest = UnityWebRequest.Get(fullEndpointUrl);
unityWebRequest.SetRequestHeader("Authorization", authToken);
yield return unityWebRequest.SendWebRequest();
CustomWebResponse customWebResponse = new CustomWebResponse();
customWebResponse.meta = new CustomWebRequestMeta();
if(unityWebRequest.responseCode == 200) {
customWebResponse.meta.isSuccess = true;
customWebResponse.statusCode = HttpStatusCode.OK;
} else {
customWebResponse.meta.isSuccess = false;
customWebResponse.statusCode = HttpStatusCode.BadRequest;
}
if(unityWebRequest.isNetworkError) {
customWebResponse.meta.reason = unityWebRequest.error;
} else {
customWebResponse.meta.reason = string.Empty;
customWebResponse.parsedData = unityWebRequest.downloadHandler.text;
}
responseAction?.Invoke(customWebResponse);
}
public void ConfirmPaypalPaymentAsync(string jsonData, string authToken, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.paypalEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, jsonData);
customWebRequest.DoSimpleAction(_topPriorityHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
#endregion
#region File Upload Methods.
public void GetPreSignedURLFromS3(string authToken, PreSignedURLFileUploadRequestBody uploadRequestBody, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = string.Format("{0}/{1}", GameSettingsManager.instance.gameSettingsSO.baseSettings.baseAPIEndpoint, GameSettingsManager.instance.gameSettingsSO.baseSettings.fileUploadPreSignURLEndpoint);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.POST, JsonUtility.ToJson(uploadRequestBody));
customWebRequest.DoSimpleAction(_uploadingHttpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
}
public void UploadFileByBytes(string authToken, string presignedURL, object dataToUpload, UploadMediaType uploadMediaType, Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string fullEndpointUrl = presignedURL;
//UploadFileWebRequest customWebRequest = new UploadFileWebRequest(fullEndpointUrl, HttpMethod.PUT_BYTEARRAY, bytesToSend, uploadMediaType);
//customWebRequest.DoFileAction(_httpClient, rA => responseAction(rA), pA => progressAction(pA), authToken);
_apiCoroutines.Add(StartCoroutine(UploadFileToS3(new System.Diagnostics.Stopwatch(), fullEndpointUrl, dataToUpload, uploadMediaType, authToken, rA => responseAction?.Invoke(rA))));
}
private IEnumerator UploadFileToS3(System.Diagnostics.Stopwatch stopwatch, string url, object dataToUpload, UploadMediaType uploadMediaType, string authToken, Action<CustomWebResponse> responseAction) {
stopwatch.Start();
UnityWebRequest uwr = new UnityWebRequest();
byte[] actualData = (byte[])dataToUpload;
if(uploadMediaType == UploadMediaType.IMAGE_PNG || uploadMediaType == UploadMediaType.Image_JPEG) {
uwr = UnityWebRequest.Put(url, actualData);
uwr.SetRequestHeader("Content-Type", StringEnum.GetStringValue(uploadMediaType));
} else if(uploadMediaType == UploadMediaType.Text_Plain) {
uwr = UnityWebRequest.Put(url, actualData);
uwr.SetRequestHeader("Content-Type", StringEnum.GetStringValue(uploadMediaType));
}
float dataSizeInMB = (actualData.Length / 1024f) / 1024;
//uwr.SetRequestHeader("Authorization", authToken);
yield return uwr.SendWebRequest();
stopwatch.Stop();
CustomWebResponse customWebResponse = new CustomWebResponse();
customWebResponse.meta = new CustomWebRequestMeta();
if(uwr.responseCode == 200) {
customWebResponse.meta.isSuccess = true;
customWebResponse.statusCode = HttpStatusCode.OK;
float timeTaken = stopwatch.Elapsed.Seconds;
customWebResponse.otherData = dataSizeInMB.ToString() + "," + timeTaken;
} else {
customWebResponse.meta.isSuccess = false;
customWebResponse.statusCode = HttpStatusCode.BadRequest;
}
if(uwr.isNetworkError) {
customWebResponse.meta.reason = uwr.error;
} else {
customWebResponse.meta.reason = string.Empty;
customWebResponse.parsedData = uwr.downloadHandler.text;
}
responseAction?.Invoke(customWebResponse);
}
private static bool TrustCertificate(object sender, X509Certificate x509Certificate, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors) {
bool isOk = true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if(sslPolicyErrors != SslPolicyErrors.None) {
for(int i = 0; i < x509Chain.ChainStatus.Length; i++) {
Debug.Log(string.Format("TrustCertificate x509Chain.ChainStatus: {0}, JSON: {1}", x509Chain.ChainStatus[i].StatusInformation, JsonUtility.ToJson(x509Chain.ChainStatus)));
if(x509Chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown) {
x509Chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
x509Chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
x509Chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
bool chainIsValid = x509Chain.Build((X509Certificate2)x509Certificate);
if(!chainIsValid) {
Debug.Log("TrustCertificate x509Chain is Invalid!");
isOk = false;
}
}
}
}
return isOk;
}
#endregion
#region Address Via IP Methods.
public void GetGeolocationAddressFromIPAsync(Action<CustomWebResponse> responseAction, Action<CustomWebResponseProgress> progressAction) {
string currentPublicIP = string.Empty;
GetCurrentPublicIP(result => {
if(result.meta.isSuccess) {
string publicIPResponse = (string)result.parsedData;
string publicIPConverted = publicIPResponse.Substring(publicIPResponse.IndexOf(":") + 1);
publicIPConverted = publicIPConverted.Substring(0, publicIPConverted.IndexOf("<"));
publicIPConverted = Regex.Replace(publicIPConverted, @"\s", "");
if(IPAddress.TryParse(publicIPConverted, out IPAddress ipAddress)) {
string fullEndpointUrl = string.Format("{0}/{1}?access_key={2}", GameSettingsManager.instance.gameSettingsSO.baseSettings.ipStackBaseEndpoint, ipAddress.ToString(), GameSettingsManager.instance.gameSettingsSO.baseSettings.ipStackAccessKey);
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), pA => progressAction(pA));
}
} else {
CustomWebResponse customWebResponse = new CustomWebResponse(HttpStatusCode.BadRequest, "Failed!", new CustomWebRequestMeta {
isSuccess = false,
reason = "CheckDNS API Failed"
});
responseAction?.Invoke(customWebResponse);
}
});
}
private void GetCurrentPublicIP(Action<CustomWebResponse> responseAction) {
string fullEndpointUrl = GameSettingsManager.instance.gameSettingsSO.baseSettings.checkDNSBaseEndpoint;
CustomWebRequest customWebRequest = new CustomWebRequest(fullEndpointUrl, HttpMethod.GET_STRING);
customWebRequest.DoSimpleAction(_normalHttpClient, rA => responseAction(rA), null);
}
#endregion
}
}

2. User Authentication UI Controller

This controller was used to access, manipulate and update the UI Screens of Authentication, viz., Login Screen, Register Screen and Forgot Password Screen.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.Utilities;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
//using UnityEngine.Analytics;
using UnityEngine.UI;
using TMPro;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       01/08/2018 15:15
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using System.Linq;
namespace Hotchform.Game.Triumph.Controllers {
public class UserAuthUIController : MonoBehaviour {
#region Public Variables.
public EmailDetailsContainer emailDetailsContainer;
public PasswordDetailsContainer passwordDetailsContainer;
#endregion
#region Private Variables.
private DBSignInEventPasser _dBSignInEventPasser = new DBSignInEventPasser();
private DBForgotPasswordEventPasser _forgotPasswordEventPasser = new DBForgotPasswordEventPasser();
private DBUserRegisterEventPasser _userRegisterEventPasser = new DBUserRegisterEventPasser();
[SerializeField] private LoginFormState _loginFormState;
[SerializeField] private Button _loginButton;
[SerializeField] private Animator _loginStateAnimator;
[SerializeField] private Button _registerButton;
[SerializeField] private GameObject _loginFormPanelContainer;
[SerializeField] private GameObject _welcomeOnBoardPanelContainer;
[SerializeField] private GameObject _registrationFormPanelContainer;
[SerializeField] private List<TMPro.TMP_InputField> _allFormInputFields;
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
EventManager.TriggerEvent(EventName.DB_FetchIPStackGeolocationAddress, new CustomEventPasser());
_loginButton.interactable = false;
_registerButton.interactable = false;
//_forgotConfirmationCodeContainer.SetActive(false);
// _dBSignInEventPasser = new DBSignInEventPasser {
// 	username = "[email protected]",
// 	password = "[email protected]",
// 	email = "[email protected]"
// };
//EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new CustomEventPasser());
}
private void OnEnable() {
EventManager.StartListening(EventName.UI_SignInComplete, OnSignInCompleteCallback);
EventManager.StartListening(EventName.UI_ForgotPasswordComplete, OnForgotPasswordCallback);
EventManager.StartListening(EventName.UI_ConfirmForgotPasswordComplete, OnConfirmForgotPasswordCallback);
EventManager.StartListening(EventName.UI_SignUpComplete, OnSignUpCompleteCallback);
EventManager.StartListening(EventName.UI_GetAllOffersForLoggedInUserComplete, OnGetAllOffersCallback);
EventManager.StartListening(EventName.UI_GetAllOrdersForLoggedInUserComplete, OnGetAllOrdersCallback);
EventManager.StartListening(EventName.UI_UserConfigurableUpdateComplete, OnGetAllUserConfigurablesCallback);
EventManager.StartListening(EventName.UI_GetAccountAll, OnGetAllAccountsCallback);
}
private void OnDisable() {
EventManager.StopListening(EventName.UI_SignInComplete, OnSignInCompleteCallback);
EventManager.StopListening(EventName.UI_ForgotPasswordComplete, OnForgotPasswordCallback);
EventManager.StopListening(EventName.UI_ConfirmForgotPasswordComplete, OnConfirmForgotPasswordCallback);
EventManager.StopListening(EventName.UI_SignUpComplete, OnSignUpCompleteCallback);
EventManager.StopListening(EventName.UI_GetAllOffersForLoggedInUserComplete, OnGetAllOffersCallback);
EventManager.StopListening(EventName.UI_GetAllOrdersForLoggedInUserComplete, OnGetAllOrdersCallback);
EventManager.StopListening(EventName.UI_UserConfigurableUpdateComplete, OnGetAllUserConfigurablesCallback);
EventManager.StopListening(EventName.UI_GetAccountAll, OnGetAllAccountsCallback);
}
#endregion
#region UI Input Receivers Methods.
public void SetEmailAddress(string emailString) {
if(_loginFormState == LoginFormState.MAIN) {
emailString = emailString.ToLowerInvariant();
if(_dBSignInEventPasser == null)
_dBSignInEventPasser = new DBSignInEventPasser();
_loginButton.interactable = true;
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
if(isEmail) {
_dBSignInEventPasser.email = emailString;
_dBSignInEventPasser.username = emailString;
_forgotPasswordEventPasser.username = emailString;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.LONG);
// emailDetailsContainer.iconImage.color = Color.red;
// emailDetailsContainer.horizontalDividerImage.color = Color.red;
// emailDetailsContainer.emailInputFieldText.color = Color.red;
}
}
if(_loginFormState == LoginFormState.FORGOT_PASSWORD) {
emailString = emailString.ToLowerInvariant();
_loginButton.interactable = false;
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
if(isEmail) {
_dBSignInEventPasser.email = emailString;
_dBSignInEventPasser.username = emailString;
_loginButton.interactable = true;
_forgotPasswordEventPasser.username = emailString;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.LONG);
}
}
}
public void EnterEmailDetails() {
emailDetailsContainer.iconImage.color = Color.white;
emailDetailsContainer.horizontalDividerImage.color = new Color32(248, 247, 247, 148);
emailDetailsContainer.emailInputFieldText.color = new Color32(50, 50, 50, 255);
}
public void EnterPasswordDetails() {
passwordDetailsContainer.iconImage.color = Color.white;
passwordDetailsContainer.horizontalDividerImage.color = new Color32(248, 247, 247, 148);
passwordDetailsContainer.passwordInputFieldText.color = new Color32(50, 50, 50, 255);
}
public void SetPassword(string password) {
if(_loginFormState == LoginFormState.MAIN) {
if(_dBSignInEventPasser == null)
_dBSignInEventPasser = new DBSignInEventPasser();
_loginButton.interactable = true;
if(password.Length >= 6) {//RegexUtils.ValidatePassword(newPassword, out string errorMessage)) {
_dBSignInEventPasser.password = password;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
}
// if(password.Length < 6) {//RegexUtils.ValidatePassword(password, out string errorMessage)) {
// 	_dBSignInEventPasser.password = password;
// 	//_loginButton.interactable = true;
// } else {
// 	StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
// 	passwordDetailsContainer.iconImage.color = Color.red;
// 	passwordDetailsContainer.horizontalDividerImage.color = Color.red;
// 	passwordDetailsContainer.passwordInputFieldText.color = Color.red;
// }
}
if(_loginFormState == LoginFormState.NEW_PASSWORD) {
_loginButton.interactable = false;
if(password.Length >= 6) {//RegexUtils.ValidatePassword(newPassword, out string errorMessage)) {
_forgotPasswordEventPasser.newPassword = password;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
}
}
}
public void OnLoginStateDownButtonClick() {
switch(_loginFormState) {
case LoginFormState.MAIN:
break;
case LoginFormState.FORGOT_PASSWORD:
_loginStateAnimator.SetTrigger("forgotToLogin");
break;
case LoginFormState.NEW_PASSWORD:
_loginStateAnimator.SetTrigger("newToForgot");
break;
default:
break;
}
}
public void OnLoginButtonClick() {
switch(_loginFormState) {
case LoginFormState.MAIN:
if(_dBSignInEventPasser == null) {
StatusBarUtility.instance.SetStatus(GameConstants.genericFieldValidationWarning, StatusType.Warning, StatusDelay.NORMAL);
return;
}
if(string.IsNullOrEmpty(_dBSignInEventPasser.email)) {
StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
return;
} else if(string.IsNullOrEmpty(_dBSignInEventPasser.password)) {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.NORMAL);
return;
} else if(string.IsNullOrEmpty(_dBSignInEventPasser.email) && string.IsNullOrEmpty(_dBSignInEventPasser.password)) {
StatusBarUtility.instance.SetStatus(GameConstants.genericFieldValidationWarning, StatusType.Warning, StatusDelay.NORMAL);
return;
}
EventManager.TriggerEvent(EventName.DB_DoSignIn, _dBSignInEventPasser);
_loginButton.interactable = false;
LoaderUtils.instance.ShowLoader();
foreach(var item in _allFormInputFields) {
if(item != null)
item.text = string.Empty;
}
break;
case LoginFormState.FORGOT_PASSWORD:
LoaderUtils.instance.ShowLoader();
EventManager.TriggerEvent(EventName.DB_DoForgotPassword, _forgotPasswordEventPasser);
break;
case LoginFormState.NEW_PASSWORD:
LoaderUtils.instance.ShowLoader();
EventManager.TriggerEvent(EventName.DB_DoConfirmForgotPassword, _forgotPasswordEventPasser);
break;
default:
break;
}
}
public void OnForgotButtonClick() {
_loginStateAnimator.SetTrigger("loginToForgot");
}
public void SetConfirmationCode(string confirmationCode) {
if(confirmationCode.Length < 5) {
_loginButton.interactable = false;
StatusBarUtility.instance.SetStatus(GameConstants.forgotPasswordConfirmationCodeLengthWarning, StatusType.Warning, StatusDelay.LONG);
} else {
_loginButton.interactable = true;
_forgotPasswordEventPasser.confirmationCode = confirmationCode;
}
}
public void SetNewPassword(string newPassword) {
_loginButton.interactable = false;
if(newPassword.Length >= 6) {//RegexUtils.ValidatePassword(newPassword, out string errorMessage)) {
_forgotPasswordEventPasser.newPassword = newPassword;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
}
}
public void SetConfirmNewPassword(string newConfirmPassword) {
_loginButton.interactable = false;
if(_forgotPasswordEventPasser.newPassword == newConfirmPassword) {//RegexUtils.ValidatePassword(newPassword, out string errorMessage)) {
_loginButton.interactable = true;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
}
}
public void SetRegisterFirstName(string firstName) {
_registerButton.interactable = false;
// if(string.IsNullOrEmpty(firstName))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validFirstNameWarning, StatusType.Warning, StatusDelay.NORMAL);
// else
_userRegisterEventPasser.firstName = firstName;
}
public void SetRegisterLastName(string lastName) {
_registerButton.interactable = false;
// if(string.IsNullOrEmpty(lastName))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validLastNameWarning, StatusType.Warning, StatusDelay.NORMAL);
// else
_userRegisterEventPasser.lastName = lastName;
}
public void SetRegisterStreet(string street) {
_registerButton.interactable = false;
if(_userRegisterEventPasser.address == null)
_userRegisterEventPasser.address = new DBAddressEventPasser();
// if(string.IsNullOrEmpty(street))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validStreetAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
// else
_userRegisterEventPasser.address.street = street;
}
public void SetRegisterPlace(string place) {
_registerButton.interactable = false;
if(_userRegisterEventPasser.address == null)
_userRegisterEventPasser.address = new DBAddressEventPasser();
// if(string.IsNullOrEmpty(place))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validAreaAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
// else
_userRegisterEventPasser.address.place = place;
}
public void SetRegisterPincode(string pincode) {
_registerButton.interactable = false;
if(_userRegisterEventPasser.address == null)
_userRegisterEventPasser.address = new DBAddressEventPasser();
// if(string.IsNullOrEmpty(pincode))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validPincodeAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
// else 
_userRegisterEventPasser.address.pincode = pincode;
}
public void SetRegisterEmailAddress(string emailString) {
emailString = emailString.ToLowerInvariant();
_registerButton.interactable = false;
bool isEmail = RegexUtils.ValidateEmail(emailString);
// if(isEmail) {
_userRegisterEventPasser.email = emailString;
// } else {
//StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.LONG);
//}
}
public void SetRegisterPassword(string password) {
_registerButton.interactable = false;
// if(password.Length >= 6) {//RegexUtils.ValidatePassword(password, out string errorMessage)) {
_userRegisterEventPasser.password = password;
// } else {
//StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
//}
}
public void SetRegisterPasswordConfirm(string confirmPassword) {
_registerButton.interactable = false;
if(!string.IsNullOrEmpty(_userRegisterEventPasser.password) && confirmPassword == _userRegisterEventPasser.password) {
// if(string.IsNullOrEmpty(_userRegisterEventPasser.firstName))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validFirstNameWarning, StatusType.Warning, StatusDelay.LONG);
// if(string.IsNullOrEmpty(_userRegisterEventPasser.lastName))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validLastNameWarning, StatusType.Warning, StatusDelay.LONG);
// if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.street))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validStreetAddressWarning, StatusType.Warning, StatusDelay.LONG);
// if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.place))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validAreaAddressWarning, StatusType.Warning, StatusDelay.LONG);
// if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.pincode))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validPincodeAddressWarning, StatusType.Warning, StatusDelay.LONG);
// if(string.IsNullOrEmpty(_userRegisterEventPasser.email))
// 	StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.LONG);
_registerButton.interactable = true;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.passwordNotMatchingWarning, StatusType.Error, StatusDelay.LONG);
}
}
public void OnUserRegisterButtonClick() {
bool check = false;
if(!string.IsNullOrEmpty(_userRegisterEventPasser.password)) {
if(string.IsNullOrEmpty(_userRegisterEventPasser.firstName))
StatusBarUtility.instance.SetStatus(GameConstants.validFirstNameWarning, StatusType.Warning, StatusDelay.LONG);
if(string.IsNullOrEmpty(_userRegisterEventPasser.lastName))
StatusBarUtility.instance.SetStatus(GameConstants.validLastNameWarning, StatusType.Warning, StatusDelay.LONG);
if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.street))
StatusBarUtility.instance.SetStatus(GameConstants.validStreetAddressWarning, StatusType.Warning, StatusDelay.LONG);
if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.place))
StatusBarUtility.instance.SetStatus(GameConstants.validAreaAddressWarning, StatusType.Warning, StatusDelay.LONG);
if(_userRegisterEventPasser.address == null || string.IsNullOrEmpty(_userRegisterEventPasser.address.pincode))
StatusBarUtility.instance.SetStatus(GameConstants.validPincodeAddressWarning, StatusType.Warning, StatusDelay.LONG);
if(string.IsNullOrEmpty(_userRegisterEventPasser.email))
StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.LONG);
if(string.IsNullOrEmpty(_userRegisterEventPasser.password))
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
else
check = true;
} else {
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Error, StatusDelay.LONG);
check = false;
}
if(check) {
foreach(var item in _allFormInputFields) {
item.text = string.Empty;
}
EventManager.TriggerEvent(EventName.DB_DoSignUp, _userRegisterEventPasser);
_registerButton.interactable = false;
LoaderUtils.instance.ShowLoader();
} else {
_registerButton.interactable = true;
StatusBarUtility.instance.SetStatus(GameConstants.validPasswordWarning, StatusType.Warning, StatusDelay.LONG);
}
//Analytics.CustomEvent("User SignUp", new Dictionary<string, object> {
//	{ "email", _userRegisterEventPasser.email },
//	{ "dateTime", DateTime.Now.ToString("ddMMyyyy_hhMMss") }
//});
}
#endregion
#region Event Callbacks.
private void OnSignInCompleteCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser eventPasser = (UIGenericEventPasser)customEventPasser;
Debug.Log(string.Format("UI_SignInComplete: {0}", JsonUtility.ToJson(eventPasser)));
if(eventPasser.isError || eventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
//StatusBarUtility.instance.SetStatus("Logged In Successfully!", StatusType.Info, StatusDelay.LONG);
EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
}
}
private void OnForgotPasswordCallback(CustomEventPasser customEventPasser) {
LoaderUtils.instance.HideLoader();
UIGenericEventPasser eventPasser = (UIGenericEventPasser)customEventPasser;
Debug.Log(string.Format("UI_ForgotPasswordComplete: {0}", JsonUtility.ToJson(eventPasser)));
if(eventPasser.isError || eventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.onForgotPasswordWrongConfirmationCodeWarning, StatusType.Error, StatusDelay.LONG);
} else {
StatusBarUtility.instance.SetStatus(GameConstants.onForgotPasswordSuccessInfo, StatusType.Info, StatusDelay.LONG);
_loginStateAnimator.SetTrigger("forgotToNew");
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen, UnityEngine.SceneManagement.LoadSceneMode.Single));
//_forgotConfirmationCodeContainer.SetActive(true);
//_forgotConfirmButton.interactable = false;
}
}
private void OnConfirmForgotPasswordCallback(CustomEventPasser customEventPasser) {
LoaderUtils.instance.HideLoader();
UIGenericEventPasser eventPasser = (UIGenericEventPasser)customEventPasser;
Debug.Log(string.Format("UI_ConfirmForgotPasswordComplete: {0}", JsonUtility.ToJson(eventPasser)));
if(eventPasser.isError || eventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
_loginButton.interactable = true;
}
else {
StatusBarUtility.instance.SetStatus(GameConstants.accountUpdateSuccessInfo, StatusType.Info, StatusDelay.LONG);
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen, UnityEngine.SceneManagement.LoadSceneMode.Single));
_loginButton.interactable = true;
//_forgotPasswordPanelController.Hide();
_loginStateAnimator.SetTrigger("newToLogin");
}
}
private void OnSignUpCompleteCallback(CustomEventPasser customEventPasser) {
LoaderUtils.instance.HideLoader();
UIGenericEventPasser eventPasser = (UIGenericEventPasser)customEventPasser;
Debug.Log(string.Format("UI_SignUpComplete: {0}", JsonUtility.ToJson(eventPasser)));
if(eventPasser.isError || eventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
_welcomeOnBoardPanelContainer.SetActive(false);
_registrationFormPanelContainer.SetActive(true);
} else {
StatusBarUtility.instance.SetStatus(GameConstants.registrationSuccessfullInfo, StatusType.Info, StatusDelay.LONG);
_registrationFormPanelContainer.SetActive(false);
_welcomeOnBoardPanelContainer.SetActive(true);
}
}
private void OnGetAllOffersCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
//SetupOffersHolder();
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
}
}
private void OnGetAllOrdersCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
#region Notifications Hided due to TRI-168 request.
//StatusBarUtility.instance.SetStatus("All Orders and Offers Fetched Successfully!", StatusType.Info, StatusDelay.LONG);
#endregion
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen, UnityEngine.SceneManagement.LoadSceneMode.Single));
//LoaderUtils.instance.HideLoader();
}
}
private void OnGetAllUserConfigurablesCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
EventManager.TriggerEvent(EventName.DB_GetAccountAll, new DBGetAllAccountEventPasser(false, string.Empty));
//LoaderUtils.instance.HideLoader();
}
}
private void OnGetAllAccountsCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
LoaderUtils.instance.HideLoader();
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen));
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
EventManager.TriggerEvent(EventName.LM_DataUpdateComplete_FromUI, new CustomEventPasser());
}
}
#endregion
public void SetLoginFormState(LoginFormState stateToSet) {
_loginFormState = stateToSet;
}
}
[Serializable]
public class EmailDetailsContainer {
public TextMeshProUGUI emailInputFieldText;
public Image iconImage;
public Image horizontalDividerImage;
}
[Serializable]
public class PasswordDetailsContainer {
public TextMeshProUGUI passwordInputFieldText;
public Image iconImage;
public Image horizontalDividerImage;
}
[Serializable]
public enum LoginFormState {
MAIN,
FORGOT_PASSWORD,
NEW_PASSWORD
}
}

3. Home Screen UI Controller

Our Home Screen shows various data types from different scriptables at the same time. It shows all the previous Order Summary and Order Details of the logged in user, current available Offers, transition buttons to Shop Screen, Account Screen and QR Screen.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.Scriptables;
using Hotchform.Game.Triumph.UIHelpers;
using Hotchform.Game.Triumph.Utilities;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
//using UnityEngine.Analytics;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       24/08/2018 20:55
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using System.IO;
namespace Hotchform.Game.Triumph.Controllers {
public class HomeScreenUIController : MonoBehaviour {
#region Public Variables.
public CurrentShowcasePanel currentShowcasePanel;
public UnityEvent OnOfferTabButtonClick;
public UnityEvent OnOrdersTabButtonClick;
#endregion
#region Private Variables.
//[SerializeField] private UserOrderUIHolder _userOrderUIHolder;
[SerializeField] private TMPro.TMP_Text _myTriumphText;
[SerializeField] private Image _topSliderImage;
[SerializeField] private Sprite _offersSliderSprite;
[SerializeField] private Sprite _offersTabSprite;
[SerializeField] private Sprite _ordersSliderSprite;
[SerializeField] private ProductShowcaseListItemUI _showcaseListItemPrefab;
[SerializeField] private Transform _showcaseListContentTrans;
[SerializeField] private Image _sliderItemImagePrefab;
[SerializeField] private Transform _sliderContent;
[SerializeField] private Image _sliderPaginationItemImagePrefab;
[SerializeField] private Transform _sliderPaginationPanel;
[SerializeField] private ScrollSnapRect _scrollSnapRect;
private List<ProductShowcaseListItemUI> _showcaseListItems = new List<ProductShowcaseListItemUI>();
//[SerializeField] private CustomScrollViewSnapUtil _orderSummaryScrollSnapRect;
[SerializeField] private Transform _orderSummaryListContent;
[SerializeField] private OrderSummaryListItemUI _orderSummaryItemPrefab;
[SerializeField] private Transform _orderSummaryPaginationListContent;
[SerializeField] private Image _orderSummaryPaginationItemPrefab;
[SerializeField] private Transform _offerSummaryListContent;
[SerializeField] private Transform _offerSummaryPaginationListContent;
[SerializeField] private UserOfferListItemUI _offerSummaryItemPrefab;
[SerializeField] private Image _offerSummaryPaginationItemPrefab;
[SerializeField] private Image _orderDetailsPaginationItemPrefab;
[SerializeField] private Transform _orderDetailsListContent;
[SerializeField] private Transform _orderDetailsPaginationContent;
[SerializeField] private OrderDetailsListItemUI _orderDetailsItemPrefab;
[SerializeField] private HorizontalScrollSnap _orderSummaryScrollSnapRect;
[SerializeField] private ScrollSnapRect _offerSummaryScrollSnapRect;
[SerializeField] private ScrollSnapRect _orderDetailsScrollSnapRect;
[SerializeField] private Animator _orderFullDetailsAnimator;
[SerializeField] private TMPro.TMP_Text _billingAddressPlaceText;
[SerializeField] private TMPro.TMP_Text _billingAddressStreetText;
[SerializeField] private TMPro.TMP_Text _billingAddressPincodeText;
[SerializeField] private TMPro.TMP_Text _shippingAddressPlaceText;
[SerializeField] private TMPro.TMP_Text _shippingAddressStreetText;
[SerializeField] private TMPro.TMP_Text _shippingAddressPincodeText;
[SerializeField] private TMPro.TMP_Text _subTotalChargesText;
[SerializeField] private TMPro.TMP_Text _shippingChargesText;
[SerializeField] private TMPro.TMP_Text _vatChargesText;
[SerializeField] private TMPro.TMP_Text _grandTotalChargesText;
[SerializeField] private TMPro.TMP_Text _appliedOrderCouponText;
private bool _isTabClickedAndProcessing = false;
private int _lastTabClikCount = 0;
private int _currentShowcaseItemSelection = 0;
private int _lastNumberOfOrders = 0;
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
//EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
//LoaderUtils.instance.ShowLoader(true);
//SetupOffersHolder();
//SetupOrdersUIHolder();
//_offerSummaryScrollSnapRect.enabled = false;
_myTriumphText.text = "Ihre Bestellungen werden geladen. Bitte haben Sie einen Augenblick Geduld.";
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
SetupAllUIs();
}
private void OnEnable() {
EventManager.StartListening(EventName.UI_ApplyCouponToCartComplete, OnApplyCouponCallback);
EventManager.StartListening(EventName.UI_GetAllOffersForLoggedInUserComplete, OnGetAllOffersCallback);
EventManager.StartListening(EventName.UI_GetAllOrdersForLoggedInUserComplete, OnGetAllOrdersCallback);
}
private void OnDisable() {
EventManager.StopListening(EventName.UI_ApplyCouponToCartComplete, OnApplyCouponCallback);
EventManager.StopListening(EventName.UI_GetAllOffersForLoggedInUserComplete, OnGetAllOffersCallback);
EventManager.StopListening(EventName.UI_GetAllOrdersForLoggedInUserComplete, OnGetAllOrdersCallback);
}
#endregion
#region Callback Methods.
private void OnApplyCouponCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
StatusBarUtility.instance.SetStatus(GameConstants.offerApplySuccessInfo, StatusType.Info, StatusDelay.NORMAL);
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
}
//LoaderUtils.instance.HideLoader();
}
private void OnGetAllOffersCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
//SetupOffersHolder();
SetupAllUIs();
//EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
}
//SetupAllUIs();
LoaderUtils.instance.HideLoader();
}
private void OnGetAllOrdersCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
#region Notifications Hided due to TRI-168 request.
//StatusBarUtility.instance.SetStatus("All Orders and Offers Fetched Successfully!", StatusType.Info, StatusDelay.LONG);
#endregion
if(DataManager.instance.userOrdersSO.info.anyOrderUpdated) {
SetupAllUIs();
}
LoaderUtils.instance.HideLoader();
}
EventManager.TriggerEvent(EventName.LM_DataUpdateComplete_FromUI, new CustomEventPasser());
LoaderUtils.instance.HideLoader();
}
#endregion
#region Custom Methods.
private void SetupAllUIs() {
_lastNumberOfOrders = DataManager.instance.userOrdersSO.info.orders.Count;
//LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_myTriumphText.text = "Ihre Bestellungen werden geladen. Bitte haben Sie einen Augenblick Geduld.";
// if(DataManager.instance.userOffersSO.info.offers.Count != 0 && DataManager.instance.userOffersSO.info.offers.Any(o => !o.isUsed)) {
// 	_currentShowcaseItemSelection = 0;
// 	currentShowcasePanel = CurrentShowcasePanel.COUPON;
// 	SetupOffersHolder();
// } else {
// 	_currentShowcaseItemSelection = 0;
// 	currentShowcasePanel = CurrentShowcasePanel.ORDER;
// 	OnOrdersTabButtonClick?.Invoke();
// }
ToggleOrderFullDetailsAnimator(false);
//OnOfferTabButtonClick?.Invoke();
#region Setting up Sliders For Default Offer Tab.
//_scrollSnapRect.enabled = false;
_showcaseListItems = new List<ProductShowcaseListItemUI>();
foreach(Transform item in _showcaseListContentTrans) {
Destroy(item.gameObject);
}
foreach(Transform orderSummaryItemTrans in _orderSummaryListContent) {
Destroy(orderSummaryItemTrans.gameObject);
}
foreach(Transform child in _orderDetailsListContent) {
Destroy(child.gameObject);
}
foreach(Transform child in _orderDetailsPaginationContent) {
Destroy(child.gameObject);
}
foreach(Transform child in _orderSummaryPaginationListContent) {
Destroy(child.gameObject);
}
_offerSummaryScrollSnapRect.enabled = false;
foreach(Transform item in _offerSummaryListContent) {
Destroy(item.gameObject);
}
foreach(Transform item in _offerSummaryPaginationListContent) {
Destroy(item.gameObject);
}
if(DataManager.instance.userOffersSO.info != null && DataManager.instance.userOffersSO.info.offers != null && DataManager.instance.userOffersSO.info.offers.Count > 0) {
foreach (var item in DataManager.instance.userOffersSO.info.offers) {
if(!item.isUsed) {
UserOfferListItemUI listItemUI = Instantiate<UserOfferListItemUI>(_offerSummaryItemPrefab, _offerSummaryListContent);
Image pagination = Instantiate<Image>(_offerSummaryPaginationItemPrefab, _offerSummaryPaginationListContent);
if(DataManager.instance.userOffersSO.info.offers.Where(o => !o.isUsed).ToList().Count <= 1)
pagination.enabled = false;
else
pagination.enabled = true;
listItemUI.uIHolder.SetData(item);
}
}
if(DataManager.instance.userOffersSO.info.offers.Any(o => !o.isUsed)) {
ProductShowcaseListItemUI offersListItemUI = Instantiate<ProductShowcaseListItemUI>(_showcaseListItemPrefab, _showcaseListContentTrans);
offersListItemUI.showcaseType = ProductShowcaseType.Offer;
offersListItemUI.isSelected = true;
offersListItemUI.UpdateSelection(offersListItemUI.isSelected);
_showcaseListItems.Add(offersListItemUI);
var tab = _showcaseListItems.Find(s => s.showcaseType == ProductShowcaseType.Offer);
if(tab != null && tab.itemButton != null) {
tab.itemButton.onClick.RemoveAllListeners();
tab.itemButton.onClick.AddListener(() => {
if(currentShowcasePanel != CurrentShowcasePanel.COUPON) {
OnOfferTabButtonClick.Invoke();
currentShowcasePanel = CurrentShowcasePanel.COUPON;
}
});
tab.itemImage.sprite = _offersTabSprite;
}
_offerSummaryScrollSnapRect.enabled = true;
_offerSummaryScrollSnapRect._doInit = true;
LoaderUtils.instance.HideLoader();
OnOfferTabButtonClick?.Invoke();
}
//_userOfferUIHolder.redeemOfferButton.interactable = true;
//_userOfferUIHolder.redeemOfferButton.onClick.AddListener(() => {
//    LoaderUtils.instance.ShowLoader();
//    EventManager.TriggerEvent(EventName.DB_ApplyCouponToCart, new DBApplyCouponEventPasser(_userOfferUIHolder.GetData().copoun_code, ApplyCouponAction.apply));
//});
} else {
// UserOfferListItemUI listItemUI = Instantiate<UserOfferListItemUI>(_offerSummaryItemPrefab, _offerSummaryListContent);
// Image pagination = Instantiate<Image>(_offerSummaryPaginationItemPrefab, _offerSummaryPaginationListContent);
// pagination.enabled = false;
// listItemUI.uIHolder.SetData(new UserOfferData(string.Empty, "No Offers For You At This Time!"));
//_userOfferUIHolder.redeemOfferButton.interactable = false;
LoaderUtils.instance.HideLoader();
}
//LoaderUtils.instance.HideLoader();
if(DataManager.instance.userOrdersSO.info != null && DataManager.instance.userOrdersSO.info.orders != null && DataManager.instance.userOrdersSO.info.orders.Count > 0) {
var ordersReordered = DataManager.instance.userOrdersSO.info.orders.OrderByDescending(o => o.updatedAt).ToList();
for(int i = 0; i < ordersReordered.Count; i++) {
UserOrderData userOrderData = ordersReordered[i];
ProductShowcaseListItemUI orderListItemUI = Instantiate<ProductShowcaseListItemUI>(_showcaseListItemPrefab, _showcaseListContentTrans);
orderListItemUI.showcaseType = ProductShowcaseType.Order;
orderListItemUI.isSelected = false;
orderListItemUI.UpdateSelection(orderListItemUI.isSelected);
orderListItemUI.uuid = userOrderData.orderNo;
orderListItemUI.updatedAt = userOrderData.updatedAt;
_showcaseListItems.Add(orderListItemUI);
if(userOrderData.product.Count > 0) { //&& userOrderData.product[0].files != null && userOrderData.product[0].files.Count > 0 && userOrderData.product[0].files.Any(f => f.featuredType == FileFeatureType.small.ToString() && f.mediaType == FileMediaType.Image.ToString())) {
List<string> productIds = new List<string>();
foreach(var item in userOrderData.product) {
if(item.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_material") {
var mainProduct = DataManager.instance.publicProductsSO.info.products.Find(p => p.selectedMaterials.Any(pmi => pmi.id == item.id));//DataManager.instance.publicProductsSO.info.products.Find(p => p.selectedMaterials.Find(pmi => pmi.id == item.id).id == item.id);
if(mainProduct != null)
productIds.Add(mainProduct.id);
} else {
productIds.Add(item.id);
}
}
//var productIds = userOrderData.product.Select(p => p.id).ToList();
//productIds.AddRange(userOrderData.product.Where(pm => !string.IsNullOrEmpty(p.product_id)).Select(p => p.product_id).ToList());
//Debug.Log(string.Format("Remove After Debugging: productIds -> {0}", string.Join( ",", productIds.ToArray())));
for(int j = 0; j < productIds.Count; j++) {
var product = DataManager.instance.publicProductsSO.info.products.Find(p => p.id == productIds[j]);
if(product != null && product.files != null && product.files.Any(f => f.mediaType == FileMediaType.Image.ToString() && f.featuredType == FileFeatureType.small.ToString())) {
var file = product.files.Find(f => f.mediaType == FileMediaType.Image.ToString() && f.featuredType == FileFeatureType.small.ToString());
string fileUuid = string.Empty;
if(file != null) {
fileUuid = file.fileDataUuid;
FileData fileData = FilesDownloaderManager.instance.filesDownloaderSO.GetFileData(fileUuid);
if(fileData != null) {
if(fileData.HasDownloaded) {
if(_showcaseListItems != null && _showcaseListItems[_showcaseListItems.IndexOf(orderListItemUI)].itemImage != null) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
_showcaseListItems[_showcaseListItems.IndexOf(orderListItemUI)].itemImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(fileData.localURI, false);
if(sprite != null) {
_showcaseListItems[_showcaseListItems.IndexOf(orderListItemUI)].itemImage.sprite = sprite;
}
}
}
break;
}
if(!fileData.HasDownloaded && fileData.progress < 0.5f) {
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
}
} else {
file.fileDataUuid = string.Empty;
FilesDownloaderManager.instance.CheckAndDownloadAsync(FileType.Image, file.mediaFormat, file.mediaUrl, fA => file.fileDataUuid = fA.uuid, null);
}
}
}
}
}
#region Setting Up Order Summary List Items.
OrderSummaryListItemUI orderSummaryItemUI = Instantiate<OrderSummaryListItemUI>(_orderSummaryItemPrefab, _orderSummaryListContent);
Instantiate<Image>(_orderDetailsPaginationItemPrefab, _orderSummaryPaginationListContent);
//OrderDetailsListItemUI orderDetailsItemUI = Instantiate<OrderDetailsListItemUI>(_orderDetailsItemPrefab, _orderDetailsListContent);
//Instantiate<Image>(_orderDetailsPaginationItemPrefab, _orderDetailsPaginationContent);
long myLong = long.Parse(userOrderData.orderDate.ToString());
var orderDate = DateUtils.GetEpochDateTime(myLong).ToString("dd.MM.yyyy");
string createdDateExtended = "vom " + orderDate;
string[] orderNoSplits = userOrderData.orderNo.Split('_');
string orderTitle = orderNoSplits.Length == 2 ? "#" + orderNoSplits[1].ToString() : "#" + userOrderData.orderNo;
string totalProductsCount = userOrderData.product.Count.ToString();
string orderTotalPrice = "€ " + userOrderData.orderFinalPrice.ToString("F2", DateUtils.GermanCulture);
orderSummaryItemUI.SetData(orderTitle, createdDateExtended, totalProductsCount, orderTotalPrice);
//orderDetailsItemUI.orderFullData = new OrderFullData(productName, createdDateExtended, orderDetailsExtended, friends, shippingAddress, billingAddress, userOrderData.calculatePrice.cartSubtotal, userOrderData.calculatePrice.totalShiping, userOrderData.calculatePrice.totaltax, userOrderData.orderFinalPrice);
//orderDetailsItemUI.SetUI();
#endregion
}
if(DataManager.instance.userOffersSO.info != null && !DataManager.instance.userOffersSO.info.offers.Any(o => !o.isUsed)) {
currentShowcasePanel = CurrentShowcasePanel.ORDER;
_showcaseListItems[0].UpdateSelection(true);
_currentShowcaseItemSelection = 0;
_orderSummaryScrollSnapRect.gameObject.SetActive(true);
//_orderSummaryScrollSnapRect.GoToScreen(0);
//_orderSummaryScrollSnapRect._doInit = true;
OnOrdersTabButtonClick?.Invoke();
// _orderDetailsScrollSnapRect.ScrollToPage(0);
// _orderDetailsScrollSnapRect._doInit = true;
} else {
//_orderSummaryScrollSnapRect.GoToScreen(0);
//_orderSummaryScrollSnapRect._doInit = true;
}
//_orderDetailsScrollSnapRect._doInit = true;
//_orderDetailsScrollSnapRect.ScrollToPage(0);
}
LoaderUtils.instance.HideLoader();
for(int i = 0; i < _showcaseListItems.Count; i++) {
var listItem = _showcaseListItems[i];
listItem.itemButton.onClick.AddListener(() => {
//if(!_isTabClickedAndProcessing) {
//_isTabClickedAndProcessing = true;
if(!listItem.isSelected) {
_lastTabClikCount++;
_currentShowcaseItemSelection = _showcaseListItems.IndexOf(listItem);
//_orderDetailsScrollSnapRect.ScrollToPage(_currentShowcaseItemSelection);
_orderSummaryScrollSnapRect.GoToScreen(_currentShowcaseItemSelection);
List<string> fileUUids = new List<string>();
switch(listItem.showcaseType) {
case ProductShowcaseType.Offer:
currentShowcasePanel = CurrentShowcasePanel.COUPON;
// foreach(var item in DataManager.instance.userOffersSO.info.offers) {
// 	fileUUids.AddRange(item.files.Where(f => f.featuredType == FileFeatureType.large.ToString() && f.mediaType == FileMediaType.Image.ToString()).Select(s => s.fileDataUuid).ToList());
// }
// ResetImageSliders(fileUUids);
//_topSliderImage.sprite = _offersSliderSprite;
break;
case ProductShowcaseType.Order:
if(currentShowcasePanel != CurrentShowcasePanel.ORDER) {
//_orderSummaryScrollSnapRect._doInit = true;
_orderDetailsScrollSnapRect._doInit = true;
OnOrdersTabButtonClick?.Invoke();
}
int requiredIndex = _currentShowcaseItemSelection;
if(DataManager.instance.userOffersSO.info.offers.Any(o => !o.isUsed))
requiredIndex = _currentShowcaseItemSelection - 1;
_orderSummaryScrollSnapRect.GoToScreen(requiredIndex);
_orderDetailsScrollSnapRect.ScrollToPage(0);
currentShowcasePanel = CurrentShowcasePanel.ORDER;
break;
default:
currentShowcasePanel = CurrentShowcasePanel.COUPON;
//_topSliderImage.sprite = _offersSliderSprite;
// foreach(var item in DataManager.instance.userOffersSO.info.offers) {
// 	fileUUids.AddRange(item.files.Where(f => f.featuredType == FileFeatureType.large.ToString() && f.mediaType == FileMediaType.Image.ToString()).Select(s => s.fileDataUuid).ToList());
// }
// ResetImageSliders(fileUUids);
break;
}
listItem.isSelected = true;
listItem.UpdateSelection(listItem.isSelected);
//ResetImageSliders(fileUUids);
}
if(listItem.isSelected) {
foreach(var item in _showcaseListItems) {
if(item != listItem) {
item.isSelected = false;
item.UpdateSelection(item.isSelected);
}
}
}
//_isTabClickedAndProcessing = false;
//}
});
}
#endregion
_myTriumphText.text = "Meine Triumphe";
}
private void ResetImageSliders(List<string> fileDataUUids) {
_scrollSnapRect.enabled = false;
foreach(Transform item in _sliderPaginationPanel) {
Destroy(item.gameObject);
}
foreach(Transform item in _sliderContent)
Destroy(item.gameObject);
// if(_lastTabClikCount > 5) {
// 	Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Texture2D Objects on a Scene Change:</color> " + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// 	foreach(var item in ImageUtils.instantiatedTexturesToDeleteWithinScene) {
// 		//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 		Destroy(item);
// 		//DeleteInstantiatedTexture2D(item);
// 	}
// 	Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Texture2D Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedTexturesToDeleteWithinScene.Count);
// 	ImageUtils.instantiatedTexturesToDeleteWithinScene = new HashSet<Texture2D>();
// 	Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>Deleting Runtime Instantiated Sprite Objects on a Scene Change:</color> " + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// 	foreach(var item in ImageUtils.instantiatedSpritesToDeleteWithinScene) {
// 		//totalSize += Profiler.GetRuntimeMemorySizeLong(item);
// 		Destroy(item);
// 		//DeleteInstantiatedTexture2D(item);
// 	}
// 	Debug.Log(DateUtils.GetEpochDateTime(DateTime.UtcNow.GetUnixTime()).ToLongTimeString() + "<color=RED>All Runtime Instantiated Sprite Objects on a Scene Change Deleted Successfully:</color> " + ImageUtils.instantiatedSpritesToDeleteWithinScene.Count);
// 	ImageUtils.instantiatedSpritesToDeleteWithinScene = new HashSet<Sprite>();
// 	_lastTabClikCount = 0;
// }
if(fileDataUUids.Count == 0) {
Instantiate<Image>(_sliderItemImagePrefab, _sliderContent);
Instantiate<Image>(_sliderPaginationItemImagePrefab, _sliderPaginationPanel);
} else {
HashSet<string> uniqueFileDataUuids = new HashSet<string>(fileDataUUids);
for(int i = 0; i < uniqueFileDataUuids.Count; i++) {
FileData fileData = FilesDownloaderManager.instance.filesDownloaderSO.GetFileData(uniqueFileDataUuids.ToList()[i]);
if(fileData != null) {
Image sliderImage = Instantiate<Image>(_sliderItemImagePrefab, _sliderContent);
Instantiate<Image>(_sliderPaginationItemImagePrefab, _sliderPaginationPanel);
if(fileData.HasDownloaded && File.Exists(fileData.localURI)) {
if(sliderImage != null) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
sliderImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(fileData.localURI, true);
if(sprite != null)
sliderImage.sprite = sprite;
}
}
} else {
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded && File.Exists(fileData.localURI)) {
if(sliderImage != null) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
sliderImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(fileData.localURI, true);
if(sprite != null)
sliderImage.sprite = sprite;
}
}
}
};
}
} else {
Instantiate<Image>(_sliderItemImagePrefab, _sliderContent);
Instantiate<Image>(_sliderPaginationItemImagePrefab, _sliderPaginationPanel);
}
}
}
_scrollSnapRect.enabled = true;
_scrollSnapRect._doInit = true;
}
//private void GetSprite(string filePath, Action<Sprite> spriteAction) {
//	Sprite NewSprite;
//	ImageUtils.LoadTextureViaWebRequest(filePath, tA => {
//		if(tA != null) {
//			NewSprite = Sprite.Create(tA, new Rect(0, 0, tA.width, tA.height), new Vector2(0, 0), 100f, 0, SpriteMeshType.Tight);
//			//GameObject.Destroy(SpriteTexture);
//			spriteAction?.Invoke(NewSprite);
//		} else {
//			spriteAction?.Invoke(null);
//		}
//	});
//}
private void SetupOffersHolder() {
//LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
//_offerSummaryScrollSnapRect.enabled = true;
//_offerSummaryScrollSnapRect._doInit = true;
//_userOfferUIHolder.userOffersButton.interactable = true;
if(DataManager.instance.userOffersSO.info != null && DataManager.instance.userOffersSO.info.offers != null && DataManager.instance.userOffersSO.info.offers.Count > 0) {
foreach (var item in DataManager.instance.userOffersSO.info.offers) {
if(!item.isUsed) {
UserOfferListItemUI listItemUI = Instantiate<UserOfferListItemUI>(_offerSummaryItemPrefab, _offerSummaryListContent);
Image pagination = Instantiate<Image>(_offerSummaryPaginationItemPrefab, _offerSummaryPaginationListContent);
if(DataManager.instance.userOffersSO.info.offers.Count == 1)
pagination.enabled = false;
else
pagination.enabled = true;
listItemUI.uIHolder.SetData(item);
}
}
//if(DataManager.instance.userOffersSO.info.offers.Any(o => !o.isUsed)) {
ProductShowcaseListItemUI offersListItemUI = Instantiate<ProductShowcaseListItemUI>(_showcaseListItemPrefab, _showcaseListContentTrans);
offersListItemUI.showcaseType = ProductShowcaseType.Offer;
offersListItemUI.isSelected = true;
offersListItemUI.UpdateSelection(offersListItemUI.isSelected);
_showcaseListItems.Add(offersListItemUI);
var tab = _showcaseListItems.Find(s => s.showcaseType == ProductShowcaseType.Offer);
if(tab != null && tab.itemButton != null) {
tab.itemButton.onClick.RemoveAllListeners();
tab.itemButton.onClick.AddListener(() => {
if(currentShowcasePanel != CurrentShowcasePanel.COUPON) {
OnOfferTabButtonClick.Invoke();
currentShowcasePanel = CurrentShowcasePanel.COUPON;
}
});
tab.itemImage.sprite = _offersTabSprite;
}
_offerSummaryScrollSnapRect.enabled = true;
_offerSummaryScrollSnapRect._doInit = true;
LoaderUtils.instance.HideLoader();
//}
OnOfferTabButtonClick?.Invoke();
//_userOfferUIHolder.redeemOfferButton.interactable = true;
//_userOfferUIHolder.redeemOfferButton.onClick.AddListener(() => {
//    LoaderUtils.instance.ShowLoader();
//    EventManager.TriggerEvent(EventName.DB_ApplyCouponToCart, new DBApplyCouponEventPasser(_userOfferUIHolder.GetData().copoun_code, ApplyCouponAction.apply));
//});
} else {
// UserOfferListItemUI listItemUI = Instantiate<UserOfferListItemUI>(_offerSummaryItemPrefab, _offerSummaryListContent);
// Image pagination = Instantiate<Image>(_offerSummaryPaginationItemPrefab, _offerSummaryPaginationListContent);
// pagination.enabled = false;
// listItemUI.uIHolder.SetData(new UserOfferData(string.Empty, "No Offers For You At This Time!"));
//_userOfferUIHolder.redeemOfferButton.interactable = false;
LoaderUtils.instance.HideLoader();
}
//LoaderUtils.instance.HideLoader();
}
// private void SetupOrdersUIHolder() {
// 	LoaderUtils.instance.HideLoader();
// 	_userOrderUIHolder.userOrdersButton.interactable = true;
// 	_userOrderUIHolder.userOrdersButton.onClick.AddListener(() => {
// 		if(currentShowcasePanel != CurrentShowcasePanel.ORDER) {
// 			OnOrdersTabButtonClick.Invoke();
// 			currentShowcasePanel = CurrentShowcasePanel.ORDER;
// 		}
// 	});
// 	if(DataManager.instance.userOrdersSO.info != null && DataManager.instance.userOrdersSO.info.orders != null && DataManager.instance.userOrdersSO.info.orders.Count > 0) {
// 		_userOrderUIHolder.SetData(DataManager.instance.userOrdersSO.info.orders.Last());
// 	} else {
// 		_userOrderUIHolder.SetData(null);
// 	}
// }
public void OnOpenOrderDetailsPanel() {
foreach(Transform child in _orderDetailsListContent) {
Destroy(child.gameObject);
}
foreach(Transform child in _orderDetailsPaginationContent) {
Destroy(child.gameObject);
}
var ordersReordered = DataManager.instance.userOrdersSO.info.orders.OrderByDescending(o => o.updatedAt).ToList();
var userOrderData = ordersReordered.Find(o => o.orderNo == _showcaseListItems[_currentShowcaseItemSelection].uuid);
string shippingAddress = "No Shipping Address Assigned";
string billingAddress = "No Billing Address Assigned";
_billingAddressPlaceText.text = userOrderData.address.billAddress.place;
_billingAddressStreetText.text = userOrderData.address.billAddress.street;
_billingAddressPincodeText.text = userOrderData.address.billAddress.pincode;
_shippingAddressPlaceText.text = userOrderData.address.shippingAddress.place;
_shippingAddressStreetText.text = userOrderData.address.shippingAddress.street;
_shippingAddressPincodeText.text = userOrderData.address.shippingAddress.pincode;
shippingAddress = userOrderData.address.shippingAddress.street + "\n" + userOrderData.address.shippingAddress.pincode + ", " + userOrderData.address.shippingAddress.place;
billingAddress = userOrderData.address.billAddress.street + "\n" + userOrderData.address.billAddress.pincode + ", " + userOrderData.address.billAddress.place;
foreach (var product in userOrderData.product) {
OrderDetailsListItemUI orderDetailsItemUI = Instantiate<OrderDetailsListItemUI>(_orderDetailsItemPrefab, _orderDetailsListContent);
Image paginationImage = Instantiate<Image>(_orderDetailsPaginationItemPrefab, _orderDetailsPaginationContent);
if(userOrderData.product.Count == 1) {
paginationImage.enabled = false;
} else {
paginationImage.enabled = true;
}
long myLong = long.Parse(userOrderData.orderDate.ToString());
var orderDate = DateUtils.GetEpochDateTime(myLong).ToString("dd.MM.yyyy");
if(product.quantity > 1)
orderDate += " (" + product.quantity + "x)";
string createdDateExtended = "Mein TRIUMPH vom " + orderDate;
string orderDetailsExtended = string.Empty;
List<FriendProfileData> friends = new List<FriendProfileData>();
// string orderTitle = "Product Not Found";
// if(userOrderData.product[0].lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main")
// 	orderTitle = userOrderData.product.Count > 1 ? userOrderData.product[0].title + " +" + (userOrderData.product.Count - 1) : userOrderData.product[0].title;
// else {
// 	var mainProduct = DataManager.instance.publicProductsSO.info.products.Find(p => p.selectedMaterials.Find(pmi => pmi.id == userOrderData.product[0].id).id == userOrderData.product[0].id);
// 	orderTitle = userOrderData.product.Count > 1 ? mainProduct.title + "-" + userOrderData.product[0].title + " +" + (userOrderData.product.Count - 1) :  mainProduct.title + "-" + userOrderData.product[0].title;
// }
//for(int x = 0; x < userOrderData.product.Count; x++) {
//	if(x == 0)
//		orderTitle = userOrderData.product[x].title;
//	else
//		orderTitle += ", " + userOrderData.product[x].title;
//}
string productName = "Product Not Found";
if(DataManager.instance.userConfigurableProductSO.info.allUserConfigurableProducts.Any(ucp => product.user_configure_product_id == ucp.product_id)) {
var firstUserConfigurableProduct = DataManager.instance.userConfigurableProductSO.info.allUserConfigurableProducts.FindLast(ucp => product.user_configure_product_id == ucp.product_id);
string newStoryDate = string.Empty;
string newStoryAddress = string.Empty;
if(firstUserConfigurableProduct.dateAndTime != null && firstUserConfigurableProduct.dateAndTime.startDate > 0)
newStoryDate = DateUtils.GetEpochDateTime(firstUserConfigurableProduct.dateAndTime.startDate).ToString("dd.MM.yyyy");
if(firstUserConfigurableProduct.address != null && !string.IsNullOrEmpty(firstUserConfigurableProduct.address.address) && firstUserConfigurableProduct.address.address != "0")
newStoryAddress = firstUserConfigurableProduct.address.address;
if(!string.IsNullOrEmpty(newStoryDate) && !string.IsNullOrEmpty(newStoryAddress)) {
orderDetailsExtended = "am <b>" +
newStoryDate +
"</b>   in <b>" +
firstUserConfigurableProduct.address.address +
"</b>";
}
if(!string.IsNullOrEmpty(newStoryDate) && string.IsNullOrEmpty(newStoryAddress)) {
orderDetailsExtended = "am <b>" +
newStoryDate;
}
if(string.IsNullOrEmpty(newStoryDate) && !string.IsNullOrEmpty(newStoryAddress)) {
orderDetailsExtended = "in <b>" +
firstUserConfigurableProduct.address.address +
"</b>";
}
foreach(var friendItem in DataManager.instance.usersDataSO.info.listOfUsers.users.Where(us => firstUserConfigurableProduct.people.Contains(us.uuid)).Select(u => u.accountData).ToList()) {
if(friendItem.isPublic) {
FriendProfileData friendProfileData = new FriendProfileData {
firstName = friendItem.firstName,
lastName = friendItem.lastName,
emailAddress = friendItem.email
};
if(friendItem.profilePic != null && !string.IsNullOrEmpty(friendItem.profilePic.fileDataUuid)) {
var fileData = FilesDownloaderManager.instance.filesDownloaderSO.GetFileData(friendItem.profilePic.fileDataUuid);
if(fileData != null) {
if(fileData.HasDownloaded) {
friendProfileData.localImageURI = fileData.localURI;
}
if(!fileData.HasDownloaded && Math.Abs(fileData.progress) < Mathf.Epsilon) {
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
}
}
}
friends.Add(friendProfileData);
}
}
} else {
orderDetailsExtended = "Downloading Scan Details from the Server...";
}
string productImageFileUUid = string.Empty;
string productId;
if(product.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_material" && DataManager.instance.publicProductsSO.info.products.Find(p => p.selectedMaterials.Any(pmi => pmi.id == product.id)).id == product.id) {
productId = DataManager.instance.publicProductsSO.info.products.Find(p => p.selectedMaterials.Any(pmi => pmi.id == product.id)).id;
} else {
productId = product.id;
}
var fetchedProduct = DataManager.instance.publicProductsSO.info.products.Find(p => p.id == productId);
productName = fetchedProduct.title;
switch(productName.ToLowerInvariant()){
case "bock":
productName = "Rehbock";
break;
case "hirsch":
productName = "Rothirsch";
break;
case "muffel":
productName = "Muffelwidder";
break;
default:
productName = "Rehbock";
break;
}
// if(fetchedProduct.showSizes)
// 	productName += string.Format(" (ca. {0})", product.size);
if(fetchedProduct.showSizes) {
if(fetchedProduct != null) {
if(fetchedProduct.sizes.big.size == product.size)
productName += " - Groß";
else if(fetchedProduct.sizes.small.size == product.size)
productName += " - Klein";
else
productName += " - Groß";
}
}
if(fetchedProduct != null && fetchedProduct.files != null && fetchedProduct.files.Any(f => f.mediaType == FileMediaType.Image.ToString() && f.featuredType == FileFeatureType.large.ToString())) {
var file = fetchedProduct.files.Find(f => f.mediaType == FileMediaType.Image.ToString());
productImageFileUUid = file.fileDataUuid;
}
if(product.files.Any(p=> p.mediaType == FileMediaType.Image.ToString()))
productImageFileUUid = product.files.Find(p=> p.mediaType == FileMediaType.Image.ToString()).fileDataUuid;
string orderDetailProductId = product.id;
orderDetailsItemUI.orderFullData = new OrderFullData(orderDetailProductId, productName, createdDateExtended, orderDetailsExtended, friends, shippingAddress, billingAddress, userOrderData.calculatePrice.cartSubtotal, 
userOrderData.calculatePrice.totalShiping, userOrderData.calculatePrice.totaltax, userOrderData.orderFinalPrice, productImageFileUUid);
orderDetailsItemUI.SetUI();
}
_subTotalChargesText.text = "€ " + userOrderData.calculatePrice.cartSubtotal.ToString("F2", DateUtils.GermanCulture);
_shippingChargesText .text= "€ " + userOrderData.calculatePrice.totalShiping.ToString("F2", DateUtils.GermanCulture);
_vatChargesText.text = "€ " + userOrderData.calculatePrice.totaltax.ToString("F2", DateUtils.GermanCulture);
_grandTotalChargesText.text = "€ " + userOrderData.orderFinalPrice.ToString("F2", DateUtils.GermanCulture);
if(!string.IsNullOrEmpty(userOrderData.copounCode) && DataManager.instance.userOffersSO.info.offers.Any(o => o.copoun_code == userOrderData.copounCode)) {
var selectedOfferData = DataManager.instance.userOffersSO.info.offers.Find(o => o.copoun_code == userOrderData.copounCode);
_appliedOrderCouponText.text = "<cspace=-0.5em>--</cspace> Gutschein " + (selectedOfferData.discountType == DiscountType.percentage.ToString() ? selectedOfferData.percentage + "%" : "€ " + userOrderData.orderDiscountAmount.ToString("F2", DateUtils.GermanCulture));
} else {
_appliedOrderCouponText.text = string.Empty;
}
_orderDetailsScrollSnapRect._doInit = true;
_orderDetailsScrollSnapRect.ScrollToPage(0);
//_orderDetailsScrollSnapRect.enabled = true;
//canvas.sortingOrder = 5;
//_orderDetailsScrollSnapRect._doInit = true;
//_orderDetailsCustomSnapUtil.SnapToPage(_currentShowcaseItemSelection);
//_orderDetailsScrollSnapRect._doInit = true;
//_orderDetailsScrollSnapRect.ScrollToPage(_currentShowcaseItemSelection - 1);
//LoaderUtils.instance.HideLoader();
}
public void OnCloseOrderDetailsPanel() {
_orderDetailsScrollSnapRect._doInit = true;
_orderDetailsScrollSnapRect.ScrollToPage(0);
foreach(Transform child in _orderDetailsListContent) {
Destroy(child.gameObject);
}
foreach(Transform child in _orderDetailsPaginationContent) {
Destroy(child.gameObject);
}
_orderDetailsScrollSnapRect._doInit = true;
//LoaderUtils.instance.HideLoader();
}
private void DoAllInitsForSnapRects() {
//_orderSummaryScrollSnapRect._doInit = true;
_orderDetailsScrollSnapRect._doInit = true;
//_orderSummaryScrollSnapRect.ScrollToPage(_currentShowcaseItemSelection);
_orderDetailsScrollSnapRect.ScrollToPage(_currentShowcaseItemSelection);
}
public void LoadHuntingAndCollectingScene() {
//EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HuntingAndCollectingScreen));
NativeCamera.Permission permission = NativeCamera.CheckPermission();
switch(permission) {
case NativeCamera.Permission.Denied:
StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
break;
case NativeCamera.Permission.ShouldAsk:
NativeCamera.Permission requestPermission = NativeCamera.RequestPermission();
switch(requestPermission) {
case NativeCamera.Permission.Denied:
StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
break;
case NativeCamera.Permission.ShouldAsk:
break;
case NativeCamera.Permission.Granted:
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HuntingAndCollectingScreen));
break;
default:
break;
}
break;
case NativeCamera.Permission.Granted:
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HuntingAndCollectingScreen));
break;
default:
StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
break;
}
}
public void LoadShopScene() {
if(DataManager.instance.publicProductsSO.info.products.Any(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main")) {
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.ShopScreen));
} else {
StatusBarUtility.instance.SetStatus(GameConstants.waitingForProductsToDownloadError, StatusType.Error, StatusDelay.LONG);
}
}
public void LoadScanScene() {
// int cameraPermission = 0;
// if (!Application.HasUserAuthorization (UserAuthorization.WebCam)) {
// 	// request camera use
// 	Application.RequestUserAuthorization (UserAuthorization.WebCam);
// } else {
// 	cameraPermission = 1;
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.UserConfigurablesScreen));
// }
// // if we don't have permission, wait until we do 
// while (cameraPermission != 1) {
// 	StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
// 	// wait a sec
// 	System.Threading.Thread.Sleep(1000);
// 	// if user enables preference
// 	if (Application.HasUserAuthorization (UserAuthorization.WebCam)) {
// 		// proceed to start app
// 		cameraPermission = 1;
// 		EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.UserConfigurablesScreen));
// 	}
// }
// StartCoroutine(CheckWebCamPermession(permissionCallback => {
// 	if(permissionCallback) {
// 		EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.UserConfigurablesScreen));
// 	} else {
// 		StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
// 	}
// }));
// Use native UI to request camera permission.
//iOSCameraPermission.VerifyPermission(gameObject.name, "SampleCallback");
}
// private void SampleCallback(string permissionWasGranted) {
// 	Debug.Log("Callback.permissionWasGranted = " + permissionWasGranted);
// 	if (permissionWasGranted == "true") {
// 		// You can now use the device camera.
// 		EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.UserConfigurablesScreen));
// 	} else {
// 		// You cannot use the device camera.  You may want to display a message to the user
// 		// about changing the camera permission in the Settings app.
// 		StatusBarUtility.instance.SetStatus(GameConstants.cameraAuthorisationWarning, StatusType.Warning, StatusDelay.LONG);
// 	}
// }
private IEnumerator CheckWebCamPermession(Action<bool> permissionCallback) {
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
permissionCallback?.Invoke(Application.HasUserAuthorization(UserAuthorization.WebCam));
}
public void LoadProfileScene() {
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.ProfileScreen));
}
public void ToggleOrderFullDetailsAnimator(bool swipeUp) {
if(swipeUp) {
_orderFullDetailsAnimator.SetTrigger("swipeUp");
OnOpenOrderDetailsPanel();
} else {
_orderFullDetailsAnimator.SetTrigger("swipeDown");
//OnCloseOrderDetailsPanel();
}
}
#endregion
}
[Serializable]
public class UserOrderUIHolder {
public Button userOrdersButton;
[SerializeField] private TMPro.TMP_Text _shortorderNameText;
[SerializeField] private TMPro.TMP_Text _shortorderDetailsText;
[SerializeField] private TMPro.TMP_Text _orderLocationShortName;
[SerializeField] private TMPro.TMP_Text _orderCreatedShortDate;
[SerializeField] private TMPro.TMP_Text _shortcreatorFirstNameText;
[SerializeField] private Image _shortcreatorProfileImage;
[SerializeField] private TMPro.TMP_Text _shortorderStatusText;
[SerializeField] private TMPro.TMP_Text _fullorderNameText;
[SerializeField] private TMPro.TMP_Text _fullorderDetailsText;
[SerializeField] private TMPro.TMP_Text _fullorderLocationName;
[SerializeField] private TMPro.TMP_Text _fullorderCreatedDate;
[SerializeField] private TMPro.TMP_Text _fullcreatorFirstNameText;
[SerializeField] private Image _fullcreatorProfileImage;
[SerializeField] private Image _packageHandOverImage;
[SerializeField] private Image _packageOnTheWayImage;
[SerializeField] private Image _inDeliveryImage;
[SerializeField] private Image _parcelDelivered;
[SerializeField] private TMPro.TMP_Text _orderBillingAddressText;
[SerializeField] private TMPro.TMP_Text _orderShippingAddressText;
[SerializeField] private TMPro.TMP_Text _orderSubTotalText;
[SerializeField] private TMPro.TMP_Text _orderTotalShippingText;
[SerializeField] private TMPro.TMP_Text _orderTotalTaxText;
[SerializeField] private TMPro.TMP_Text _orderGrandTotalText;
[SerializeField] private Button _openFullDetailsButton;
[SerializeField] private Color _orderStatusActiveColor;
[SerializeField] private Color _orderStatusInActiveColor;
[SerializeField] private UserOrderData _orderData;
public void SetData(UserOrderData data) {
this._orderData = data;
if(_orderData == null) {
_openFullDetailsButton.interactable = false;
_shortorderNameText.text = "You haven't Placed Any Order Yet!";
_shortorderDetailsText.text = string.Empty;
_shortcreatorFirstNameText.text = string.Empty;
_shortorderStatusText.text = string.Empty;
_shortcreatorProfileImage.gameObject.SetActive(false);
} else {
_shortorderNameText.text = _orderData.orderType.ToUpper();
_fullorderNameText.text = _orderData.orderType.ToUpper();
long myLong = long.Parse(_orderData.orderDate.ToString());
var orderDate = DateUtils.GetEpochDateTime(myLong).ToString("dd.MM.yyyy");
string detailsString = "am";
detailsString += "<u><link=\"orderCreatedShortDate\"><b>" +
orderDate +
"</b></link></u> in <u><link=\"orderLocationShortName\"><b>\n" +
_orderData.address.billAddress.place +
"</b></link></u> mit";
_shortorderDetailsText.text = detailsString;
_orderLocationShortName.text = "in " + _orderData.address.billAddress.place;
_orderCreatedShortDate.text = "am " + orderDate;
_fullorderLocationName.text = "in " + _orderData.address.billAddress.place;
_fullorderCreatedDate.text = "am " + orderDate;
_fullorderDetailsText.text = detailsString;
var creatorData = DataManager.instance.usersDataSO.GetUserDataOfUser(_orderData.customerId);
if(creatorData == null || creatorData.accountData == null || string.IsNullOrEmpty(creatorData.accountData.firstName)) {
_shortcreatorFirstNameText.text = string.Empty;
_fullcreatorFirstNameText.text = string.Empty;
_shortcreatorProfileImage.gameObject.SetActive(true);
_fullcreatorProfileImage.gameObject.SetActive(true);
//Analytics.CustomEvent("Home Screen Orders", new Dictionary<string, object> {
//	{ "username", DataManager.instance.GetCurrentLoggedInAccountData().username },
//	{ "problem", "Couldn't find Account for the Order's Creator with CustomerID: " + _orderData.customerId },
//	{ "dateTime", DateTime.Now.ToString("ddMMyyyy_hhMMss") }
//});
} else {
_shortcreatorFirstNameText.text = "mit " + creatorData.accountData.firstName;
_fullcreatorFirstNameText.text = "mit " + creatorData.accountData.firstName;
if(creatorData.accountData.profilePic != null && !string.IsNullOrEmpty(creatorData.accountData.profilePic.fileDataUuid)) {
_shortcreatorProfileImage.gameObject.SetActive(true);
_fullcreatorProfileImage.gameObject.SetActive(true);
if(FilesDownloaderManager.instance.filesDownloaderSO.info.files.Any(f => f.uuid == creatorData.accountData.profilePic.fileDataUuid)) {
var fileData = FilesDownloaderManager.instance.filesDownloaderSO.info.files.Find(f => f.uuid == creatorData.accountData.profilePic.fileDataUuid);
if(!fileData.HasDownloaded && Math.Abs(fileData.progress) < Mathf.Epsilon) {
LoaderUtils.instance.ShowLoader();
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
}
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded) {
if(_shortcreatorProfileImage && _fullcreatorProfileImage) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
_shortcreatorProfileImage.sprite = sprite;
_fullcreatorProfileImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(fileData.localURI, false);
if(sprite != null) {
_shortcreatorProfileImage.sprite = sprite;
_fullcreatorProfileImage.sprite = sprite;
}
}
}
}
};
}
}
}
_shortorderStatusText.text = _orderData.orderStatus;
bool check = Enum.TryParse<OrderStatus>(_orderData.orderStatus, true, out OrderStatus orderStatus);
if(check) {
switch(orderStatus) {
case OrderStatus.completed:
_packageHandOverImage.color = _orderStatusActiveColor;
_packageOnTheWayImage.color = _orderStatusActiveColor;
_inDeliveryImage.color = _orderStatusActiveColor;
_parcelDelivered.color = _orderStatusActiveColor;
break;
case OrderStatus.inprogress:
_packageHandOverImage.color = _orderStatusActiveColor;
_packageOnTheWayImage.color = _orderStatusActiveColor;
_inDeliveryImage.color = _orderStatusActiveColor;
_parcelDelivered.color = _orderStatusInActiveColor;
break;
case OrderStatus.hold:
_packageHandOverImage.color = _orderStatusActiveColor;
_packageOnTheWayImage.color = _orderStatusActiveColor;
_inDeliveryImage.color = _orderStatusInActiveColor;
_parcelDelivered.color = _orderStatusInActiveColor;
break;
case OrderStatus.refund:
_packageHandOverImage.color = _orderStatusActiveColor;
_packageOnTheWayImage.color = _orderStatusInActiveColor;
_inDeliveryImage.color = _orderStatusInActiveColor;
_parcelDelivered.color = _orderStatusInActiveColor;
break;
default:
_packageHandOverImage.color = _orderStatusInActiveColor;
_packageOnTheWayImage.color = _orderStatusInActiveColor;
_inDeliveryImage.color = _orderStatusInActiveColor;
_parcelDelivered.color = _orderStatusInActiveColor;
break;
}
} else {
_packageHandOverImage.color = _orderStatusInActiveColor;
_packageOnTheWayImage.color = _orderStatusInActiveColor;
_inDeliveryImage.color = _orderStatusInActiveColor;
_parcelDelivered.color = _orderStatusInActiveColor;
}
_orderBillingAddressText.text = _orderData.address.billAddress.place + "\n" + _orderData.address.billAddress.pincode + " " + _orderData.address.billAddress.street;
_orderShippingAddressText.text = _orderData.address.shippingAddress.place + "\n" + _orderData.address.shippingAddress.pincode + " " + _orderData.address.shippingAddress.street;
_orderSubTotalText.text = _orderData.priceCurrency + " " + _orderData.calculatePrice.cartSubtotal;
_orderTotalShippingText.text = _orderData.priceCurrency + " " + _orderData.calculatePrice.totalShiping;
_orderTotalTaxText.text = _orderData.priceCurrency + " " + _orderData.calculatePrice.totaltax;
_orderGrandTotalText.text = _orderData.priceCurrency + " " + _orderData.orderFinalPrice;
_openFullDetailsButton.interactable = true;
}
}
public UserOrderData GetData() {
return this._orderData;
}
}
[Serializable]
public enum CurrentShowcasePanel {
COUPON,
ORDER
}
}

4. New Story UI Controller

Every new scan done by the user is a type of story told from user’s perspective using Augmented Reality and Image Processing technologies. This controller creates, manipulates and update the creation process of the New Story itself.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.UIHelpers;
using Hotchform.Game.Triumph.Utilities;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
//using UnityEngine.Analytics;
using UnityEngine.Events;
using UnityEngine.UI;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       16/08/2018 14:53
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
namespace Hotchform.Game.Triumph.Controllers {
public class NewStoryUIController : MonoBehaviour {
#region Public Variables.
#endregion
#region Private Variables.
private DBLastConfigurableEventPasser _dBLastConfigurableEventPasser;
[SerializeField] private UnityEvent _onSendInvitationEvent;
//[SerializeField] private UnityEvent _onUserConfigurableCreatedEvent;
[SerializeField] private GameObject _peopleSearchContentObj;
[SerializeField] private PeopleSearchListItem _peopleSearchListItemPrefab;
[SerializeField] private Button _scanFirstStartButton;
[SerializeField] private Button _sendInvitationButton;
[SerializeField] private TMPro.TMP_InputField _invitationFullNameField;
[SerializeField] private TMPro.TMP_Text _selectedAddressText;
[SerializeField] private TMPro.TMP_Text _selectedDateRangeText;
[SerializeField] private GameObject _selectedUserProfileContainer;
[SerializeField] private Image _selectedUserProfileImage;
[SerializeField] private TMPro.TMP_Text _selectedUserName;
[SerializeField] private TMPro.TMP_Text _selectedCounterText;
[SerializeField] private TMPro.TMP_Text _selectedModelType;
[SerializeField] private TMPro.TMP_Text _enteredEngravingText;
[SerializeField] private DatePickerUtility _datePickerUtility;
[SerializeField] private Sprite _tickSprite;
[SerializeField] private Image _dateSelectorToggleImage;
[SerializeField] private Image _addressSelectorToggleImage;
[SerializeField] private Image _usersSelectorToggleImage;
[SerializeField] private Image _modelTypeSelectorToggleImage;
[SerializeField] private Image _engravingSelectorToggleImage;
[SerializeField] private TMPro.TMP_InputField _addressInput;
//[SerializeField] private TMPro.TMP_Text _markerScreenPriceDetailsText;
//[SerializeField] private Image _modelTypeImage;
//[SerializeField] private Sprite _bockModelTypeSprite;
//[SerializeField] private Sprite _hirschModelTypeSprite;
//[SerializeField] private Sprite _muffelModelTypeSprite;
private List<PeopleSearchListItem> _selectedPeople = new List<PeopleSearchListItem>();
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
//EventManager.TriggerEvent(EventName.DB_FetchIPStackGeolocationAddress, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
CreatePeopleSearchList();
// Start service before querying location
//Input.location.Start();
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
_dBLastConfigurableEventPasser.address = new DBAddressEventPasser();
//ar geolocationAddress = DataManager.instance.tempDataSO.info.lastGeolocationAddress;
// if(geolocationAddress != null) {
// 	_dBLastConfigurableEventPasser.address.pincode = geolocationAddress.zip;
// 	_dBLastConfigurableEventPasser.address.place = geolocationAddress.city + ", " + geolocationAddress.country_name;
// 	_dBLastConfigurableEventPasser.address.street = geolocationAddress.region_name;
// 	_addressInput.text = _dBLastConfigurableEventPasser.address.place;
// 	_selectedAddressText.text = _dBLastConfigurableEventPasser.address.place;
// } else {
// 	_dBLastConfigurableEventPasser.address.pincode = "PLZ43210";
// 	_dBLastConfigurableEventPasser.address.place = "Berlin, Germany";
// 	_dBLastConfigurableEventPasser.address.street = "Kirchner";
// }
//_selectedDateRangeText.text = string.Empty;
//_selectedAddressText.text = string.Empty;
//_selectedUserName.text = string.Empty;
//_selectedCounterText.text = string.Empty;
_selectedUserProfileContainer.SetActive(false);
//_selectedModelType.text = string.Empty;
//_scanFirstStartButton.interactable = false;
_sendInvitationButton.interactable = false;
_invitationFullNameField.interactable = false;
//SetDateRange();
//_datePickerUtility.SetSelectedDateRangeText();
}
private void OnEnable() {
EventManager.StartListening(EventName.UI_UserConfigurableCreationComplete, OnUserConfigurableCreationCallback);
EventManager.StartListening(EventName.UI_SendInvitationComplete, OnSendInvitationCallback);
EventManager.StartListening(EventName.UI_LoggedInUserCartUpdateComplete, OnCartUpdateCallback);
EventManager.StartListening(EventName.UI_FetchIPStackGeolocationAddressComplete, OnFetchGeolocationCallback);
}
private void OnDisable() {
EventManager.StopListening(EventName.UI_UserConfigurableCreationComplete, OnUserConfigurableCreationCallback);
EventManager.StopListening(EventName.UI_SendInvitationComplete, OnSendInvitationCallback);
EventManager.StopListening(EventName.UI_LoggedInUserCartUpdateComplete, OnCartUpdateCallback);
EventManager.StopListening(EventName.UI_FetchIPStackGeolocationAddressComplete, OnFetchGeolocationCallback);
}
#endregion
#region Custom Methods.
public void FetchGeoLocationAndSet() {
// var geolocationAddress = DataManager.instance.tempDataSO.info.lastGeolocationAddress;
// if(geolocationAddress != null && !string.IsNullOrEmpty(geolocationAddress.city)) {
// 	_dBLastConfigurableEventPasser.address.pincode = geolocationAddress.zip;
// 	_dBLastConfigurableEventPasser.address.place = geolocationAddress.region_name + ", " + geolocationAddress.country_name;
// 	_dBLastConfigurableEventPasser.address.street = geolocationAddress.city;
// 	_addressSelectorToggleImage.sprite = _tickSprite;
// 	_selectedAddressText.text = _dBLastConfigurableEventPasser.address.street;
// 	_addressInput.text = _dBLastConfigurableEventPasser.address.street;
// } else {
// 	EventManager.TriggerEvent(EventName.DB_FetchIPStackGeolocationAddress, new CustomEventPasser());
// }
}
public void ChangeTextOnDateSelection(TMPro.TMP_Text textField) {
textField.text = "bestätigen";
}
public void SetDateRange() {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
_dBLastConfigurableEventPasser.startDate = _datePickerUtility.GetSelectedStartDate();
_dBLastConfigurableEventPasser.endDate = _dBLastConfigurableEventPasser.startDate;
//_selectedDatesText.text = new DateTime(_dBLastConfigurableEventPasser.startDate).ToShortDateString();
_dateSelectorToggleImage.sprite = _tickSprite;
// _scanFirstStartButton.interactable = _dBLastConfigurableEventPasser.address != null && _dBLastConfigurableEventPasser.startDate != 0 && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)
// 	? true
// 	: false;
}
public void SetStreetAddress(string streetAddress) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
if(_dBLastConfigurableEventPasser.address == null)
_dBLastConfigurableEventPasser.address = new DBAddressEventPasser();
_dBLastConfigurableEventPasser.address.street = streetAddress;
if(string.IsNullOrEmpty(_dBLastConfigurableEventPasser.address.pincode))
_dBLastConfigurableEventPasser.address.pincode = "0";
if(string.IsNullOrEmpty(_dBLastConfigurableEventPasser.address.place))
_dBLastConfigurableEventPasser.address.place = "0";
if(_dBLastConfigurableEventPasser.latitude <= 0)
StartCoroutine(GetLocation());
//if(_dBLastConfigurableEventPasser.address.AllSet())
_dateSelectorToggleImage.sprite = _tickSprite;
// if(_dBLastConfigurableEventPasser.address != null && _dBLastConfigurableEventPasser.startDate != 0 && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
// 	_scanFirstStartButton.interactable = true;
// } else {
// 	_scanFirstStartButton.interactable = false;
// }
_addressSelectorToggleImage.sprite = _tickSprite;
_selectedAddressText.text = _dBLastConfigurableEventPasser.address.street;
}
public void SetAreaAddress(string areaAddress) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
if(_dBLastConfigurableEventPasser.address == null)
_dBLastConfigurableEventPasser.address = new DBAddressEventPasser();
_dBLastConfigurableEventPasser.address.place = areaAddress;
if(_dBLastConfigurableEventPasser.latitude <= 0)
StartCoroutine(GetLocation());
_addressSelectorToggleImage.sprite = _tickSprite;
_selectedAddressText.text = _dBLastConfigurableEventPasser.address.place;
// if(_dBLastConfigurableEventPasser.address != null && _dBLastConfigurableEventPasser.startDate != 0 && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
// 	_scanFirstStartButton.interactable = true;
// } else {
// 	_scanFirstStartButton.interactable = false;
// }
}
public void EnterEngraving(string engraving) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
// var lastConfigurable = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct;
// lastConfigurable.engraving = engraving;
_dBLastConfigurableEventPasser.engraving = engraving;
if(!string.IsNullOrEmpty(engraving))
_engravingSelectorToggleImage.sprite = _tickSprite;
_enteredEngravingText.text = engraving;
// if(_dBLastConfigurableEventPasser.address != null && _dBLastConfigurableEventPasser.startDate != 0 && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
// 	_scanFirstStartButton.interactable = true;
// } else {
// 	_scanFirstStartButton.interactable = false;
// }
}
public void SetPincode(string pincode) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
if(_dBLastConfigurableEventPasser.address == null)
_dBLastConfigurableEventPasser.address = new DBAddressEventPasser();
_dBLastConfigurableEventPasser.address.pincode = pincode;
// if(_dBLastConfigurableEventPasser.latitude <= 0)
// 	StartCoroutine(GetLocation());
_dateSelectorToggleImage.sprite = _tickSprite;
// if(_dBLastConfigurableEventPasser.address != null && _dBLastConfigurableEventPasser.startDate != 0 && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
// 	_scanFirstStartButton.interactable = true;
// } else {
// 	_scanFirstStartButton.interactable = false;
// }
}
public void SelectModelType(string type) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
_dBLastConfigurableEventPasser.modelType = type;
if(type.ToLowerInvariant() == "bock")
_selectedModelType.text = "Rehbock";
else if(type.ToLowerInvariant() == "hirsch")
_selectedModelType.text = "Rothirsch";
else if(type.ToLowerInvariant() == "muffel")
_selectedModelType.text = "Muffelwidder";
else
_selectedModelType.text = type;
_modelTypeSelectorToggleImage.sprite = _tickSprite;
if(!string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
_scanFirstStartButton.interactable = true;
} else {
_scanFirstStartButton.interactable = false;
//StatusBarUtility.instance.SetStatus("Please select a model type before proceeding ahead!", StatusType.Warning);
}
}
public void OnPeopleSelectionTick() {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
var selected = _selectedPeople.Where(s => s.IsSelected()).ToList();
if(selected.Count > 0 && DataManager.instance.usersDataSO.info.listOfUsers.users.Any(u => u.uuid == selected.ElementAt(0).username)) {
_selectedUserProfileContainer.SetActive(true);
var accountData = DataManager.instance.usersDataSO.info.listOfUsers.users.Find(u => u.uuid == selected.ElementAt(0).username).accountData;
// Set First Selected User's Profile Pic.
if(accountData != null && accountData.profilePic != null && string.IsNullOrEmpty(accountData.profilePic.fileDataUuid) && FilesDownloaderManager.instance.filesDownloaderSO.info.files.Any(f => f.uuid == accountData.profilePic.fileDataUuid)) {
var fileData = FilesDownloaderManager.instance.filesDownloaderSO.info.files.Find(f => f.uuid == accountData.profilePic.fileDataUuid);
if(!fileData.HasDownloaded && fileData.progress <= 0) {
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
}
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded) {
if(_selectedUserProfileImage != null) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
_selectedUserProfileImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(fileData.localURI);
if(sprite != null) {
_selectedUserProfileImage.sprite = sprite;
}
}
}
}
};
}
_selectedUserName.text = accountData.firstName;
} else {
_selectedUserName.text = string.Empty;
}
if(selected.Count > 1)
_selectedUserName.text += " +" + (selected.Count - 1);
else
_selectedUserName.text += string.Empty;
_usersSelectorToggleImage.sprite = _tickSprite;
_dBLastConfigurableEventPasser.selectedUserEmails = _selectedPeople.Where(s => s.selectionToggle.isOn == true).Select(s => s.email).ToList();
}
public void OnStartScanFirstClick() {
if(_dBLastConfigurableEventPasser != null && !string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType)) {
if(_dBLastConfigurableEventPasser == null)
_dBLastConfigurableEventPasser = new DBLastConfigurableEventPasser();
if(_dBLastConfigurableEventPasser.address == null || string.IsNullOrEmpty(_dBLastConfigurableEventPasser.address.street)) {
_dBLastConfigurableEventPasser.address = new DBAddressEventPasser {
place = "0",
street = "0",
pincode = "0"
};
}
if(string.IsNullOrEmpty(_dBLastConfigurableEventPasser.modelType))
_dBLastConfigurableEventPasser.modelType = "0";
if(string.IsNullOrEmpty(_dBLastConfigurableEventPasser.engraving))
_dBLastConfigurableEventPasser.engraving = "No Engraving Set";
if(_selectedPeople.Any(s => s.selectionToggle.isOn == true))
_dBLastConfigurableEventPasser.selectedUserEmails = _selectedPeople.Where(s => s.selectionToggle.isOn == true).Select(s => s.email).ToList();
else
_dBLastConfigurableEventPasser.selectedUserEmails = new List<string>();
_scanFirstStartButton.interactable = false;
LoaderUtils.instance.ShowLoader();
EventManager.TriggerEvent(EventName.DB_CreateUserConfigurable, _dBLastConfigurableEventPasser);
} else {
StatusBarUtility.instance.SetStatus(GameConstants.newStoryModelTypeNotSelectedWarning, StatusType.Warning, StatusDelay.NORMAL);
}
//_dBLastConfigurableEventPasser = null;
}
private IEnumerator GetLocation() {
yield return null;
// // First, check if user has location service enabled
// if(!Input.location.isEnabledByUser)
// 	yield break;
// // Start service before querying location
// Input.location.Start();
// // Wait until service initializes
// int maxWait = 2;
// while(Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
// 	yield return new WaitForSeconds(1);
// 	maxWait--;
// }
// // Service didn't initialize in 20 seconds
// if(maxWait < 1) {
// 	Debug.LogWarning("GetLocation Timed out");
// 	yield break;
// }
// // Connection has failed
// if(Input.location.status == LocationServiceStatus.Failed) {
// 	Debug.LogWarning("Unable to determine device location");
// 	_dBLastConfigurableEventPasser.latitude = 0;
// 	_dBLastConfigurableEventPasser.longitude = 0;
// 	yield break;
// } else {
// 	// Access granted and location value could be retrieved
// 	Debug.Log("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
// 	_dBLastConfigurableEventPasser.latitude = Input.location.lastData.latitude;
// 	_dBLastConfigurableEventPasser.longitude = Input.location.lastData.longitude;
// }
// // Stop service if there is no need to query location updates continuously
// Input.location.Stop();
}
public void CreatePeopleSearchList() {
foreach(var item in DataManager.instance.usersDataSO.info.listOfUsers.users) {
if(item.accountData != null && item.accountData.isPublic) {
if(item.accountData.username != DataManager.instance.usersDataSO.info.currentLoggedInUserSettings.uuid) {
PeopleSearchListItem instantiatedItem = Instantiate<PeopleSearchListItem>(_peopleSearchListItemPrefab, _peopleSearchContentObj.transform);
instantiatedItem.gameObject.name = item.accountData.username;
instantiatedItem.username = item.accountData.username;
instantiatedItem.email = item.accountData.email;
instantiatedItem.fullName = item.accountData.firstName + " " + item.accountData.lastName;
instantiatedItem.SetPersonName();
instantiatedItem.gameObject.SetActive(false);
_selectedPeople.Add(instantiatedItem);
if(item.accountData.profilePic != null && !string.IsNullOrEmpty(item.accountData.profilePic.fileDataUuid)) {
var fileData = FilesDownloaderManager.instance.filesDownloaderSO.info.files.Find(f => f.uuid == item.accountData.profilePic.fileDataUuid);
if(fileData != null && fileData.HasDownloaded) {
instantiatedItem.SetProfilePicFromFile(fileData.localURI);
}
}
}
}
}
}
public void UpdatePeopleSearchList(string input) {
if(string.IsNullOrEmpty(input)) {
foreach(var item in _selectedPeople) {
item.gameObject.SetActive(false);
}
} else {
var searcheableList = _selectedPeople.Where(s => s.fullName.ToLowerInvariant().Contains(input.ToLowerInvariant())).ToList();
foreach(var item in searcheableList) {
item.gameObject.SetActive(true);
}
var nonSearcheableList = _selectedPeople.Where(s => !s.fullName.ToLowerInvariant().Contains(input.ToLowerInvariant())).ToList();
foreach(var item in nonSearcheableList) {
item.gameObject.SetActive(false);
}
}
}
private string _invitedEmailAddress = string.Empty;
public void CheckAndSetInvitaionEmail(string emailAddress) {
emailAddress = emailAddress.ToLowerInvariant();
if(!RegexUtils.ValidateEmail(emailAddress)) {
StatusBarUtility.instance.SetStatus(GameConstants.validEmailAddressWarning, StatusType.Warning, StatusDelay.SHORT);
_sendInvitationButton.interactable = false;
return;
}
if(DataManager.instance.usersDataSO.info.listOfUsers.users != null && DataManager.instance.usersDataSO.info.listOfUsers.users.Count > 0 && DataManager.instance.usersDataSO.info.listOfUsers.users.Any(s => s.accountData.email == emailAddress)) {
string message = GameConstants.userAlreadyPresentInListWarning;
message = message.Replace("<email>", emailAddress);
StatusBarUtility.instance.SetStatus(message, StatusType.Warning, StatusDelay.SHORT);
_sendInvitationButton.interactable = false;
return;
}
if(emailAddress == DataManager.instance.GetCurrentLoggedInAccountData().email) {
StatusBarUtility.instance.SetStatus(GameConstants.selfInviteWarning, StatusType.Warning, StatusDelay.SHORT);
_sendInvitationButton.interactable = false;
return;
}
_invitedEmailAddress = emailAddress;
// PeopleSearchListItem instantiatedItem = Instantiate<PeopleSearchListItem>(_peopleSearchListItemPrefab, _peopleSearchContentObj.transform);
// instantiatedItem.gameObject.name = emailAddress;
// instantiatedItem.username = emailAddress;
// instantiatedItem.email = emailAddress;
// instantiatedItem.fullName = _invitationFullNameField.text;
// instantiatedItem.SetPersonName();
// _selectedPeople.Add(instantiatedItem);
_invitationFullNameField.interactable = true;
_sendInvitationButton.interactable = true;
}
public void OnInvitationEmailInputFieldSelected() {
_invitationFullNameField.interactable = false;
_sendInvitationButton.interactable = false;
}
public void OnSendInvitationButtonClick() {
_sendInvitationButton.interactable = false;
_invitationFullNameField.interactable = false;
EventManager.TriggerEvent(EventName.DB_SendInvitation, new DBSendInvitaionEventPasser(_invitedEmailAddress, _invitationFullNameField.text));
LoaderUtils.instance.ShowLoader();
_invitationFullNameField.text = string.Empty;
_invitedEmailAddress = string.Empty;
}
#endregion
#region Callback Methods.
private void OnFetchGeolocationCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser eventPasser = (UIGenericEventPasser)customEventPasser;
if(eventPasser.isError || eventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.NORMAL);
} else {
#region Notifications Hided due to TRI-168 request.
//StatusBarUtility.instance.SetStatus("Current Location Fetched Successfuly!", StatusType.Info, StatusDelay.NORMAL);
#endregion
var geolocationAddress = DataManager.instance.tempDataSO.info.lastGeolocationAddress;
_dBLastConfigurableEventPasser.address.pincode = geolocationAddress.zip;
_dBLastConfigurableEventPasser.address.place = geolocationAddress.city + ", " + geolocationAddress.country_name;
_dBLastConfigurableEventPasser.address.street = geolocationAddress.region_name;
_addressSelectorToggleImage.sprite = _tickSprite;
_selectedAddressText.text = _dBLastConfigurableEventPasser.address.street;
}
}
private void OnUserConfigurableCreationCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
_scanFirstStartButton.interactable = true;
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
_scanFirstStartButton.interactable = false;
LoaderUtils.instance.ShowLoader();
//Only for testing.
var lastConfigurable = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct;
lastConfigurable.oldthreeDscanFolder = new DataHandlers.Scriptables.OldthreeDscanFolder(DateTime.UtcNow.GetUnixTime().ToString(), "v" + Application.version + "b");
EventManager.TriggerEvent(EventName.DB_UpdateUserConfigurable, new CustomEventPasser());
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.ScanSliderScreen));
EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty, 0));
//var cartItem = DataManager.instance.userCartSO.info.product.Find(p => p.id == DataManager.instance.tempDataSO.info.lastSelectedCartItemId);
//EventManager.TriggerEvent(EventName.DB_UpdateLoggedInUserCart, new DBUpdateCartEventPasser(cartItem.id, cartItem.lang_type, cartItem.quantity, lastConfigurable.product_id, false));
//lastConfigurable.markOnImage.Add(new DataHandlers.Scriptables.MarkOnImage(1.35f, 2.35f));
//lastConfigurable.oldthreeDscanFolder = new DataHandlers.Scriptables.OldthreeDscanFolder(DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString(), Application.version + "b");
//lastConfigurable.threeDscanFile.Add(new DataHandlers.Scriptables.ThreeDscanFile("Image", "png", "https://s3.eu-central-1.amazonaws.com/triumph-snapshots/TRIUMPH_GAME_1.1.5b/10082018/Triumph_Snaps_10082018_121946922/1_rowOneSnap.png", "AllPlatforms", DateTimeOffset.Now.ToUnixTimeMilliseconds(), DateTimeOffset.Now.ToUnixTimeMilliseconds()));
}
}
private void OnSendInvitationCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
_selectedPeople.Remove(_selectedPeople.Last());
UpdatePeopleSearchList(string.Empty);
} else {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.invitationSentSuccessInfo, StatusType.Info, StatusDelay.NORMAL);
UpdatePeopleSearchList(string.Empty);
_onSendInvitationEvent?.Invoke();
}
}
private void OnCartUpdateCallback(CustomEventPasser customEventPasser) {
_scanFirstStartButton.interactable = true;
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
LoaderUtils.instance.HideLoader();
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.ScanSliderScreen));
//var mainProductData = DataManager.instance.publicProductsSO.info.products.Find(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_material" && p.id == DataManager.instance.tempDataSO.info.lastSelectedCartItemId);
//var configurableData = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct;
//if(mainProductData != null && configurableData != null) {
//	_onUserConfigurableCreatedEvent?.Invoke();
//	switch(configurableData.productType) {
//		case "Rotwild":
//			_modelTypeImage.sprite = _hirschModelTypeSprite;
//			break;
//		case "Bock":
//			_modelTypeImage.sprite = _bockModelTypeSprite;
//			break;
//		case "Muffel":
//			_modelTypeImage.sprite = _muffelModelTypeSprite;
//			break;
//		default:
//			_modelTypeImage.sprite = _bockModelTypeSprite;
//			break;
//	}
//	_markerScreenPriceDetailsText.text = mainProductData.currencyCode + " " + mainProductData.price;
//} else {
//	StatusBarUtility.instance.SetStatus("Couldn't find the selected product in server. Please report this bug to the developer!", StatusType.Bug, StatusDelay.LONG);
//}
//Analytics.CustomEvent("User Configurable Product Created", new Dictionary<string, object> {
//	{ "username", DataManager.instance.GetCurrentLoggedInAccountData().username },
//	{ "productId", lastConfigurable.product_id },
//	{ "dateTime", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK") }
//});
}
}
public void FromMarkerToSliderScreen() {
string screenShotPath = Application.persistentDataPath + "/modelMarkingWithSelections.png";
ScreenCapture.CaptureScreenshot(screenShotPath);
DataManager.instance.tempDataSO.info.lastMarkedModelScreenshotLocalURI = screenShotPath;
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.ScanSliderScreen));
}
public void LoadCartScene() {
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.CartScreen));
}
#endregion
}
}

5. Shop UI Controller

User has two options to add a product to their cart in this game, viz., either by selecting a previous Scan done or by creating a new scan using New Story module. After this process, they can select a product to which this scan needs to be linked and what type of material for 3D printing needs to be added. All products preview are shown in 3D world space inside custom UIs.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Hotchform.Game.Triumph.Managers;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Hotchform.Game.Triumph.Utilities;
using Hotchform.Game.Triumph.Utilities.Mono;
/*===============================================================
Product:    TRIUMPH
Developer:  Arpit Tyagi - [email protected]
Company:    Triumph by hochform GmbH
Date:       03-10-2018 14:37
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using Hotchform.Game.Triumph.UIHelpers;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Scriptables;
using System;
using Fabric.Crashlytics;
using System.IO;
using UnityEngine.Events;
using UnityEngine.UI.Extensions;
namespace Hotchform.Game.Triumph.Controllers {
public class ShopUIController : MonoBehaviour {
#region Public Variables.
#endregion
#region Private Variables.
[SerializeField] private Button _previousButton;
[SerializeField] private Button _nextButton;
[SerializeField] private MaterialProductUIHolder _materialProductUIHolder;
[SerializeField] private ScrollSnapRect _mainProductScrollSnapRect;
[SerializeField] private Transform _mainProductScrollContent;
[SerializeField] private Transform _mainProductPaginationImagesContent;
[SerializeField] private Transform _materialsGridLayoutPanel;
private string _currentProductId;
private string _currentMaterialProductId;
private List<MaterialSummaryListItemData> _currentMaterialProductDataList = new List<MaterialSummaryListItemData>();
private GameObject _lastInstantiatedObject;
private AssetBundle _materialProductAssetBundle;
[SerializeField] private TMP_Text _productDescriptionText;
[SerializeField] private MainProductListItemUI _mainProductListItemPrefab;
[SerializeField] private MaterialProductSummaryListItemUI _materialSummaryListItemPrefab;
[SerializeField] private TMPro.TMP_Text _productSizeText;
[SerializeField] private Image _mainProductPaginationImagePrefab;
[SerializeField] private GameObject _productOverviewPanel;
[SerializeField] private Image _productOverviewMainImage;
[SerializeField] private Transform _mainAssetObjectContainer;
[SerializeField] private Sprite _hutanstekerSprite;
[SerializeField] private Sprite _lasergravurSprite;
[SerializeField] private Sprite _miniatureTrophySprite;
[SerializeField] private GameObject _productOverviewMaterialTypePanel;
[SerializeField] private GameObject _productOverviewNonMaterialTypePanel;
[SerializeField] private TMP_Text _productOverviewNonMaterialText;
[SerializeField] private ShopUIState _currentState;
[SerializeField] private Toggle _highestSizeUnitToggle;
[SerializeField] private Text _highestSizeUnitLabelText;
[SerializeField] private Toggle _mediumSizeUnitToggle;
[SerializeField] private Text _mediumSizeUnitLabelText;
[SerializeField] private Animator _productOverviewAnimator;
[SerializeField] private List<ProductSliderSet> _productSliderSets;
[SerializeField] private List<Image> _sliderImages;
[SerializeField] private HorizontalScrollSnap _productSliderSnapper;
[SerializeField] private Button _productOverviewButton;
[SerializeField] private Button _materialisationButton;
private Material _lastMaterialToSet;
private ProductSizeInfo _lastSizeSelected;
private List<int> _currentSizesAvailable = new List<int>();
private List<PublicProductData> _usedPublicProducts = new List<PublicProductData>();
//private MainProductListItemData _lastSelectedProductData;
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
EventManager.TriggerEvent(EventName.DB_AbortAllHttpClients, new AbortHttpClientsEventPasser(true));
LoaderUtils.instance.HideLoader();
_productOverviewMaterialTypePanel.SetActive(true);
_productOverviewNonMaterialTypePanel.SetActive(false);
_highestSizeUnitToggle.isOn = true;
_highestSizeUnitToggle.gameObject.SetActive(false);
_mediumSizeUnitToggle.gameObject.SetActive(false);
_previousButton.onClick.AddListener(GetPreviousProduct);
_nextButton.onClick.AddListener(GetNextProduct);
_productOverviewButton.interactable = true;
_materialisationButton.interactable = true;
//_mainProductScrollSnapRect.Init();
UpdateUI();
}
private void OnEnable() {
EventManager.StartListening(EventName.UI_LoggedInUserCartAddComplete, OnAddToCartCallback);
EventManager.StartListening(EventName.UI_LoggedInUserCartGetComplete, OnCartGetCompleteCallback);
}
private void OnDisable() {
EventManager.StopListening(EventName.UI_LoggedInUserCartAddComplete, OnAddToCartCallback);
EventManager.StopListening(EventName.UI_LoggedInUserCartGetComplete, OnCartGetCompleteCallback);
}
#endregion
#region Custom Methods.
public void UpdateUI() {
//_mainProductScrollSnapRect.enabled = false;
if(DataManager.instance.publicProductsSO.info.products.Count <= 0) {
Debug.Log("UpdateMaterialPanelUI API Error: " + "Due to Server or Internet Connectivity Error, Couldn't Fetch new Products to Showcase!");
StatusBarUtility.instance.SetStatus(GameConstants.refetchingAfterInternetReconnectError, StatusType.Error, StatusDelay.STAY);
EventManager.TriggerEvent(EventName.GS_DataUpdateSuccessfull, new UIGenericEventPasser(GameConstants.genericNetworkFailedError, false, false));
}
foreach(Transform child in _mainProductScrollContent) {
Destroy(child.gameObject);
}
foreach(Transform child in _mainProductPaginationImagesContent) {
Destroy(child.gameObject);
}
if(DataManager.instance.publicProductsSO.info.products.Count > 0) {
if(DataManager.instance.publicProductsSO.info.products.Any(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main")) {
_usedPublicProducts = DataManager.instance.publicProductsSO.info.products.Where(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main").ToList();
foreach(var item in _usedPublicProducts) {
MainProductListItemUI itemUI = Instantiate<MainProductListItemUI>(_mainProductListItemPrefab, _mainProductScrollContent);
Instantiate<Image>(_mainProductPaginationImagePrefab, _mainProductPaginationImagesContent);
string title = item.title;
//List<string> materialIDs = item.selectedMaterials.Select(s => s.id).ToList();
List<MaterialSummaryListItemData> materialsData = new List<MaterialSummaryListItemData>();
string productType = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.productType.ToLowerInvariant();
// foreach(var materialProduct in DataManager.instance.publicProductsSO.info.products.Where(p => materialIDs.Contains(p.id)).ToList()) {
// 	if(materialProduct.title.ToLowerInvariant() == productType) {
// 		MaterialType materialType = MaterialType.Gold;
// 		if(materialProduct.productType.ToLowerInvariant() == "gold")
// 			materialType = MaterialType.Gold;
// 		else if(materialProduct.productType.ToLowerInvariant() == "silver")
// 			materialType = MaterialType.Silver;
// 		else
// 			materialType = MaterialType.Steel;
// 		materialsData.Add(new MaterialSummaryListItemData(materialProduct.id, materialType, materialProduct.title, materialProduct.lang_type));
// 	}
// }
string sizeDetails = string.Empty;
foreach (var selectedMaterial in item.selectedMaterials) {
var materialProduct = DataManager.instance.publicProductsSO.info.products.Find(m => m.id == selectedMaterial.id && m.title.ToLowerInvariant() == productType);
if(materialProduct != null) {
materialsData.Add(new MaterialSummaryListItemData(selectedMaterial.id, selectedMaterial.lang_type));
switch(materialProduct.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
sizeDetails = "ca. " + materialProduct.sizes.big.size;
break;
case ProductAssetType.normal:
sizeDetails = "ca. " + materialProduct.sizes.big.size;
break;
case ProductAssetType.glass:
sizeDetails = "Groß - " + materialProduct.sizes.big.size + "\n" + "Klein - " + materialProduct.sizes.small.size;
break;
case ProductAssetType.stand:
sizeDetails = materialProduct.sizes.big.size;
break;
default:
sizeDetails = "ca. " + materialProduct.sizes.big.size;
break;
}
}
}
string localURI = string.Empty;
if(item.files.Count > 0 && item.files.Any(f => f.featuredType == "large" && f.mediaType == FileMediaType.Image.ToString())) {
FileData fileData = FilesDownloaderManager.instance.filesDownloaderSO.GetFileData(item.files.Find(f => f.featuredType == "large" && f.mediaType == FileMediaType.Image.ToString()).fileDataUuid);
if(fileData != null) {
if(fileData.HasDownloaded && fileData.progress > 0.9f) {
localURI = fileData.localURI;
}
if(!fileData.HasDownloaded && fileData.progress > 0f && fileData.progress < 0.9f) {
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded)
localURI = fileData.localURI;
};
} else {
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded && fileData.progress > 0.9f)
localURI = fileData.localURI;
};
}
}
}
Sprite sprite;
if(!string.IsNullOrEmpty(localURI)) {
if(ImageUtils.CheckForSprite(localURI)) {
sprite = ImageUtils.GetPoolSprite(localURI);
} else {
sprite = ImageUtils.LoadNewSprite(localURI);
}
} else {
if(item.assetType.ToLowerInvariant() == "normal")
sprite = _hutanstekerSprite;
else if(item.assetType.ToLowerInvariant() == "glass")
sprite = _lasergravurSprite;
else if(item.assetType.ToLowerInvariant() == "stand")
sprite = _miniatureTrophySprite;
else
sprite = _hutanstekerSprite;
}
itemUI.SetData(new MainProductListItemData(item.id, item.title, item.description, materialsData, sprite, sizeDetails, item.assetType));
itemUI.itemButton.onClick.RemoveAllListeners();
itemUI.itemButton.onClick.AddListener(() => {
_currentState = ShopUIState.SliderView;
var data = itemUI.itemData;
OnProductOverviewClick(data);
ProductSliderSet sliderSet = _productSliderSets.Find(s => s.assetType.ToString().ToLowerInvariant() == data.assetType.ToLowerInvariant());
if(sliderSet != null) {
_sliderImages[0].sprite = sliderSet.sliderSprites[0];
_sliderImages[1].sprite = sliderSet.sliderSprites[1];
_sliderImages[2].sprite = sliderSet.sliderSprites[2];
} 
});
}
_mainProductScrollSnapRect._doInit = true;
//_mainProductScrollSnapRect.Init();
}
} else {
Debug.Log("Product List is null");
}
}
private void OnProductOverviewClick(MainProductListItemData itemData)
{
// Open the Product Overview Screen via Event Manager Scene Load funda.
// Remeber to update CustomSceneManager for that.
//_currentMaterialProductId = _currentMaterialProductDataList[_currentMaterialProductDataList.FindIndex(p => p.productId == _currentMaterialProductId)].productId;
_currentProductId = itemData.productId;
UpdateUIForProductOverview(itemData);
}
public void UpdateUIForProductOverview(MainProductListItemData itemData) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
//var publicProduct = _usedPublicProducts.Find(p => p.id == itemData.productId);
_materialProductUIHolder.CleanHolder();
_productDescriptionText.text = itemData.productDescription;
// if(!string.IsNullOrEmpty(itemData.localImageURI)) {
// 	if(ImageUtils.CheckForSprite(itemData.localImageURI)) {
// 		Sprite sprite = ImageUtils.GetPoolSprite(itemData.localImageURI);
// 		if(sprite != null) {
// 			_productOverviewPanel.GetComponent<Image>().sprite = sprite;
// 		}
// 	} else {
// 		Sprite sprite = ImageUtils.LoadNewSprite(itemData.localImageURI);
// 		if(sprite != null) {
// 			_productOverviewPanel.GetComponent<Image>().sprite = sprite;
// 		}
// 	}
// }
if(itemData.imageSprite != null) {
_productOverviewMainImage.sprite = itemData.imageSprite;
}
_productSizeText.text = itemData.sizeDetails;
_currentMaterialProductDataList = new List<MaterialSummaryListItemData>();
_currentMaterialProductDataList = itemData.materialSummaryLists;
if(_currentMaterialProductDataList != null && _currentMaterialProductDataList.Count > 0) {
_currentMaterialProductId = _currentMaterialProductDataList[0].productId;
var publicProduct = _usedPublicProducts.Find(p => p.id == itemData.productId);
if(publicProduct.assetType.ToEnum<ProductAssetType>() == ProductAssetType.glass) {
_productOverviewMaterialTypePanel.SetActive(false);
_productOverviewNonMaterialTypePanel.SetActive(true);
_productOverviewNonMaterialText.text = "Glas";
} else if(publicProduct.assetType.ToEnum<ProductAssetType>() == ProductAssetType.stand) {
_productOverviewMaterialTypePanel.SetActive(false);
_productOverviewNonMaterialTypePanel.SetActive(true);
_productOverviewNonMaterialText.text = "Trophäe aus Kunststoff, Plattform aus massivem Holz";
} else {
_productOverviewMaterialTypePanel.SetActive(true);
_productOverviewNonMaterialTypePanel.SetActive(false);
}
} else {
_productOverviewMaterialTypePanel.SetActive(false);
_productOverviewNonMaterialTypePanel.SetActive(true);
}
_productOverviewPanel.SetActive(true);
LoaderUtils.instance.HideLoader();
//_lastSelectedProductData = itemData;
//foreach(Transform child in _materialsGridLayoutPanel) {
//	Destroy(child.gameObject);
//}
//foreach(var item in itemData.materialSummaryLists) {
//	MaterialProductSummaryListItemUI summaryListItemUI = Instantiate<MaterialProductSummaryListItemUI>(_materialSummaryListItemPrefab, _materialsGridLayoutPanel);
//	summaryListItemUI.SetData(item.materialName, item.materialType);
//}
}
private void GetNextProduct() {
//LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Bottom);
//_mainProductAssetBundle.Unload(true);
_currentMaterialProductId = _currentMaterialProductDataList[_currentMaterialProductDataList.FindIndex(p => p.productId == _currentMaterialProductId) + 1].productId;
//_mainProductAssetBundle?.Unload(true);
if(_lastInstantiatedObject != null)
Destroy(_lastInstantiatedObject);
_lastInstantiatedObject = null;
UpdateMaterialPanelUI();
}
private void GetPreviousProduct() {
//LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Bottom);
//_mainProductAssetBundle.Unload(true);
_currentMaterialProductId = _currentMaterialProductDataList[_currentMaterialProductDataList.FindIndex(p => p.productId == _currentMaterialProductId) - 1].productId;
//_mainProductAssetBundle?.Unload(true);
if(_lastInstantiatedObject != null)
Destroy(_lastInstantiatedObject);
_lastInstantiatedObject = null;
UpdateMaterialPanelUI();
}
private void CheckAdjacent() {
int currentIndex = _currentMaterialProductDataList.FindIndex(p => p.productId == _currentMaterialProductId);
if(currentIndex > 0)
_previousButton.gameObject.SetActive(true);
else
_previousButton.gameObject.SetActive(false);
if(currentIndex < _currentMaterialProductDataList.Count - 1)
_nextButton.gameObject.SetActive(true);
else
_nextButton.gameObject.SetActive(false);
}
public void UpdateMaterialPanelUI(bool hasMaterials = true) {
//LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Bottom);
System.GC.Collect();
Resources.UnloadUnusedAssets();
if(_lastInstantiatedObject != null)
Destroy(_lastInstantiatedObject);
_lastInstantiatedObject = null;
if(hasMaterials) {
Debug.Log("_currentMaterialProductId: " + _currentMaterialProductId);
PublicProductData publicProductData = DataManager.instance.publicProductsSO.info.products.Find(p => p.id == _currentMaterialProductId && p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_material");
if(publicProductData != null)
StartCoroutine(SetMaterialProductUIHolder(hasMaterials, publicProductData));
else {
Debug.Log("UpdateMaterialPanelUI API BUG: " + "Couldn't Load PublicProductData. Please create bug report for the developer. Thank you!");
StatusBarUtility.instance.SetStatus(GameConstants.onBugReceivedError, StatusType.Bug, StatusDelay.NORMAL);
}
CheckAdjacent();
} else {
PublicProductData publicProductData = DataManager.instance.publicProductsSO.info.products.Find(p => p.id == _currentProductId && p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main");
StartCoroutine(SetMaterialProductUIHolder(hasMaterials, publicProductData));
_previousButton.gameObject.SetActive(false);
_nextButton.gameObject.SetActive(false);
LoaderUtils.instance.HideLoader();
}
}
private IEnumerator SetMaterialProductUIHolder(bool hasMaterials, PublicProductData publicProductData) {
Debug.Log("OnMaterialUIOpen, publicpProductData: " + JsonUtility.ToJson(publicProductData));
Resources.UnloadUnusedAssets();
if(_lastInstantiatedObject != null)
Destroy(_lastInstantiatedObject);
_lastInstantiatedObject = null;
foreach (Transform item in _materialProductUIHolder.assetBundlePrefabContainer.transform)
{
Destroy(item.gameObject);
}
_materialProductUIHolder.CleanHolder();
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
_highestSizeUnitToggle.gameObject.SetActive(false);
_mediumSizeUnitToggle.gameObject.SetActive(false);
_lastSizeSelected = publicProductData.sizes.big;
break;
case ProductAssetType.normal:
_highestSizeUnitToggle.gameObject.SetActive(false);
_mediumSizeUnitToggle.gameObject.SetActive(false);
_lastSizeSelected = publicProductData.sizes.big;
break;
case ProductAssetType.glass:
_highestSizeUnitToggle.gameObject.SetActive(true);
_mediumSizeUnitToggle.gameObject.SetActive(true);
_highestSizeUnitLabelText.text = "Groß";
_mediumSizeUnitLabelText.text = "Klein";
_lastSizeSelected = publicProductData.sizes.big;
break;
case ProductAssetType.stand:
_highestSizeUnitToggle.gameObject.SetActive(false);
_mediumSizeUnitToggle.gameObject.SetActive(false);
_lastSizeSelected = publicProductData.sizes.big;
break;
default:
_highestSizeUnitToggle.gameObject.SetActive(false);
_mediumSizeUnitToggle.gameObject.SetActive(false);
_lastSizeSelected = publicProductData.sizes.big;
break;
}
_highestSizeUnitToggle.isOn = true;
_mediumSizeUnitToggle.isOn = false;
_highestSizeUnitToggle.onValueChanged.RemoveAllListeners();
_mediumSizeUnitToggle.onValueChanged.RemoveAllListeners();
_highestSizeUnitToggle.onValueChanged.AddListener((check) => {
if(check) {
_lastSizeSelected = publicProductData.sizes.big;
_materialProductUIHolder.materialPriceText.text = "€ " + publicProductData.sizes.big.price.ToString("F2", DateUtils.GermanCulture);
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.normal && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = Vector3.zero;
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.75f;
}
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.glass && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -64f, 0f);
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.75f;
}
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.stand && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -50f, 0f);
_lastInstantiatedObject.transform.localScale *= 0.75f;
}
}
});
_mediumSizeUnitToggle.onValueChanged.AddListener((check) => {
if(check) {
_lastSizeSelected = publicProductData.sizes.small;
_materialProductUIHolder.materialPriceText.text = "€ " + publicProductData.sizes.small.price.ToString("F2", DateUtils.GermanCulture);
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.normal && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -24f, 0f);
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.5f;
}
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.glass && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -88f, 0f);
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.5f;
}
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.stand && _lastInstantiatedObject != null) {
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -74f, 0f);
_lastInstantiatedObject.transform.localScale *= 0.5f;
}
}
});
if(_mainAssetObjectContainer != null) {
Debug.Log("hasMaterials: " + hasMaterials);
if(hasMaterials) {
_mainAssetObjectContainer.gameObject.SetActive(true);
_materialProductUIHolder.nonMaterialProductImage.gameObject.SetActive(false);
//ToggleSizeButtons();
string title = "Bock";
switch(publicProductData.title.ToLowerInvariant()){
case "bock":
title = "Rehbock";
break;
case "hirsch":
title = "Rothirsch";
break;
case "muffel":
title = "Muffelwidder";
break;
default:
title = "Rehbock";
break;
}
if(publicProductData.productType.ToLowerInvariant() == "silver")
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Silber";
else if(publicProductData.productType.ToLowerInvariant() == "gold")
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Gold";
else if(publicProductData.productType.ToLowerInvariant() == "steel")
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Stahl";
else if(publicProductData.productType.ToLowerInvariant() == "crystal")
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Glas";
else if(publicProductData.productType.ToLowerInvariant() == "wood")
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Trophäe";
//_materialProductUIHolder.productTitleText.text = publicProductData.title;
_materialProductUIHolder.materialTitleText.text = "Trophäe & Material festlegen";
//_mainProductUIHolder.productTypeText.text = publicProductData.productType;
//_materialProductUIHolder.materialSizeText.text = string.Format("{0} {1}", publicProductData.size.ToString(), publicProductData.sizeUnit);
_materialProductUIHolder.materialPriceText.text = "€ " + publicProductData.sizes.big.price.ToString("F2", DateUtils.GermanCulture);
_materialProductUIHolder.decreaseQuantity.onClick.RemoveAllListeners();
_materialProductUIHolder.decreaseQuantity.onClick.AddListener(delegate {
_materialProductUIHolder.quantitySet -= 1;
if(_materialProductUIHolder.quantitySet <= 0)
_materialProductUIHolder.quantitySet = 1;
_materialProductUIHolder.quantityInput.text = _materialProductUIHolder.quantitySet.ToString();
});
_materialProductUIHolder.increaseQuantity.onClick.RemoveAllListeners();
_materialProductUIHolder.increaseQuantity.onClick.AddListener(delegate {
_materialProductUIHolder.quantitySet += 1;
if(_materialProductUIHolder.quantitySet <= 0)
_materialProductUIHolder.quantitySet = 1;
_materialProductUIHolder.quantityInput.text = _materialProductUIHolder.quantitySet.ToString();
});
_materialProductUIHolder.quantityInput.onEndEdit.RemoveAllListeners();
_materialProductUIHolder.quantityInput.onEndEdit.AddListener(delegate {
string value = _materialProductUIHolder.quantityInput.text;
if(int.TryParse(value, out int result)) {
if(result <= 0)
result = 1;
_materialProductUIHolder.quantitySet = result;
_materialProductUIHolder.quantityInput.text = result.ToString();
}
});
_materialProductUIHolder.addToCartButton.onClick.RemoveAllListeners();
_materialProductUIHolder.addToCartButton.onClick.AddListener(delegate {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_materialProductUIHolder.addToCartButton.enabled = false;
float engravingCost = 0f;
string _lastConfigurableId = string.Empty;
if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct != null) {
_lastConfigurableId = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.product_id;
if(!string.IsNullOrEmpty(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.engraving) && 
DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct .engraving != "0" && 
DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct .engraving.ToLowerInvariant() != "no engraving set") {
var mainProduct = DataManager.instance.publicProductsSO.info.products.Find(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main" && p.id == _currentProductId);
if(mainProduct != null)	
engravingCost = mainProduct.engravingCost;
}
}
string sizeToSend = "big";
if(_lastSizeSelected.size == publicProductData.sizes.big.size)
sizeToSend = "big";
else if(_lastSizeSelected.size == publicProductData.sizes.medium.size)
sizeToSend = "medium";
else if(_lastSizeSelected.size == publicProductData.sizes.small.size)
sizeToSend = "small";
else
sizeToSend = "big";
DBAddCartEventPasser eventPasser = new DBAddCartEventPasser(publicProductData.id, publicProductData.lang_type, _materialProductUIHolder.quantitySet, publicProductData.currencyCode, 
_lastSizeSelected.price, sizeToSend, publicProductData.sizeUnit, _currentProductId, _lastConfigurableId, engravingCost);
EventManager.TriggerEvent(EventName.DB_AddLoggedInUserCart, eventPasser);
});
// PublicProductFile publicProductFile = publicProductData.files.First(p => p.platformType.Equals("iOS", StringComparison.InvariantCultureIgnoreCase) && p.mediaType.ToEnum<FileMediaType>() == FileMediaType.AssetBundle);
// FileData assetFileData = FilesDownloaderManager.instance.filesDownloaderSO.info.files.Find(f => f.uuid == publicProductFile.fileDataUuid);
string objectName = publicProductData.title;
GameObject prefabToInstatiate;
yield return null;
switch(objectName.ToLowerInvariant()){
case "bock":
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.none && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.normal:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.glass:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.glass && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.stand:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.stand && pa.modelName == ModelName.bock).associatedPrefab;
break;
default:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.bock).associatedPrefab;
break;
}
break;
case "hirsch":
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.none && pa.modelName == ModelName.hirsch).associatedPrefab;
break;
case ProductAssetType.normal:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.hirsch).associatedPrefab;
break;
case ProductAssetType.glass:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.glass && pa.modelName == ModelName.hirsch).associatedPrefab;
break;
case ProductAssetType.stand:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.stand && pa.modelName == ModelName.hirsch).associatedPrefab;
break;
default:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.hirsch).associatedPrefab;
break;
}
break;
case "muffel":
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.none && pa.modelName == ModelName.muffel).associatedPrefab;
break;
case ProductAssetType.normal:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.muffel).associatedPrefab;
break;
case ProductAssetType.glass:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.glass && pa.modelName == ModelName.muffel).associatedPrefab;
break;
case ProductAssetType.stand:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.stand && pa.modelName == ModelName.muffel).associatedPrefab;
break;
default:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.muffel).associatedPrefab;
break;
}
break;
default:
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.none && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.normal:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.glass:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.glass && pa.modelName == ModelName.bock).associatedPrefab;
break;
case ProductAssetType.stand:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.stand && pa.modelName == ModelName.bock).associatedPrefab;
break;
default:
prefabToInstatiate = GameSettingsManager.instance.gameSettingsSO.baseSettings.productAssets.Find(pa => pa.asssetType == ProductAssetType.normal && pa.modelName == ModelName.bock).associatedPrefab;
break;
}
break;
}
//_lastInstantiatedObject.GetComponent<Renderer>().material.shader = Shader.Find("Mobile/VertexLit");
//_lastInstantiatedObject.transform.localRotation = Quaternion.identity;
switch(publicProductData.assetType.ToEnum<ProductAssetType>()) {
case ProductAssetType.none:
// Don't instantiate anything.
break;
case ProductAssetType.normal:
_lastInstantiatedObject = Instantiate<GameObject>(prefabToInstatiate, _materialProductUIHolder.assetBundlePrefabContainer.transform);
_lastInstantiatedObject.transform.localPosition = Vector3.zero;
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.75f;
break;
case ProductAssetType.glass:
_lastInstantiatedObject = Instantiate<GameObject>(prefabToInstatiate, _materialProductUIHolder.assetBundlePrefabContainer.transform);
_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -64f, 0f);
_lastInstantiatedObject.transform.localScale = Vector3.one * 0.75f;
break;
case ProductAssetType.stand:
_lastInstantiatedObject = Instantiate<GameObject>(prefabToInstatiate, _materialProductUIHolder.assetBundlePrefabContainer.transform);
//_lastInstantiatedObject.transform.localPosition = new Vector3(0f, -64f, 0f);
_lastInstantiatedObject.transform.localScale *= 0.75f;
break;
default:
break;
}
_lastInstantiatedObject.gameObject.AddComponent<RotateObject>();
_lastInstantiatedObject.gameObject.layer = 8;
if(publicProductData.assetType.ToEnum<ProductAssetType>() == ProductAssetType.normal) {
Material matToSet;
switch(publicProductData.productType.ToLowerInvariant()) {
case "gold":
matToSet = GameSettingsManager.instance.gameSettingsSO.baseSettings.goldMaterial;
break;
case "silver":
matToSet = GameSettingsManager.instance.gameSettingsSO.baseSettings.silverMaterial;
break;
case "steel":
matToSet = GameSettingsManager.instance.gameSettingsSO.baseSettings.steelMaterial;
break;
default:
matToSet = new Material(Shader.Find("Standard"));
break;
}
_lastInstantiatedObject.GetComponent<AssetBundleItemRecognizer>().linkedMeshRenderers.ForEach(lm => lm.material = matToSet);
}
LoaderUtils.instance.HideLoader();
} else {
_mainAssetObjectContainer.gameObject.SetActive(false);
_materialProductUIHolder.nonMaterialProductImage.gameObject.SetActive(true);
//ToggleSizeButtons();
//_materialProductUIHolder.productTitleText.text = publicProductData.title;
_materialProductUIHolder.materialTitleText.text = "Produkt auswählen";
string title = "Bock";
switch(publicProductData.title.ToLowerInvariant()){
case "bock":
title = "Rehbock";
break;
case "hirsch":
title = "Rothirsch";
break;
case "muffel":
title = "Muffelwidder";
break;
default:
title = "Rehbock";
break;
}
_materialProductUIHolder.materialDescriptionText.text = title + " | " + "Glas";
//_mainProductUIHolder.productTypeText.text = publicProductData.productType;
//_materialProductUIHolder.materialSizeText.text = string.Format("{0} {1}", publicProductData.size.ToString(), publicProductData.sizeUnit);
_materialProductUIHolder.materialPriceText.text = "€ " + publicProductData.sizes.big.price.ToString("F2", DateUtils.GermanCulture);
_materialProductUIHolder.decreaseQuantity.onClick.AddListener(delegate {
_materialProductUIHolder.quantitySet -= 1;
if(_materialProductUIHolder.quantitySet <= 0)
_materialProductUIHolder.quantitySet = 1;
_materialProductUIHolder.quantityInput.text = _materialProductUIHolder.quantitySet.ToString();
});
_materialProductUIHolder.increaseQuantity.onClick.AddListener(delegate {
_materialProductUIHolder.quantitySet += 1;
if(_materialProductUIHolder.quantitySet <= 0)
_materialProductUIHolder.quantitySet = 1;
_materialProductUIHolder.quantityInput.text = _materialProductUIHolder.quantitySet.ToString();
});
_materialProductUIHolder.quantityInput.onEndEdit.AddListener(delegate {
string value = _materialProductUIHolder.quantityInput.text;
if(int.TryParse(value, out int result)) {
if(result <= 0)
result = 1;
_materialProductUIHolder.quantitySet = result;
_materialProductUIHolder.quantityInput.text = result.ToString();
}
});
_materialProductUIHolder.addToCartButton.onClick.AddListener(delegate {
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_materialProductUIHolder.addToCartButton.enabled = false;
string _lastConfigurableId = string.Empty;
float engravingCost = 0f;
if(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct != null) {
_lastConfigurableId = DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.product_id;
if(!string.IsNullOrEmpty(DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct.engraving) && 
DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct .engraving != "0" && 
DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct .engraving.ToLowerInvariant() != "no engraving set") {
var mainProduct = DataManager.instance.publicProductsSO.info.products.Find(p => p.lang_type == GameSettingsManager.instance.gameSettingsSO.info.currentLanguageCode + "_main" && p.id == _currentProductId);
if(mainProduct != null)	
engravingCost = mainProduct.engravingCost;
}
}
string sizeToSend = "big";
if(_lastSizeSelected.size == publicProductData.sizes.big.size)
sizeToSend = "big";
else if(_lastSizeSelected.size == publicProductData.sizes.medium.size)
sizeToSend = "medium";
else if(_lastSizeSelected.size == publicProductData.sizes.small.size)
sizeToSend = "small";
else
sizeToSend = "big";
EventManager.TriggerEvent(EventName.DB_AddLoggedInUserCart, new DBAddCartEventPasser(publicProductData.id, publicProductData.lang_type, _materialProductUIHolder.quantitySet, publicProductData.currencyCode, 
_lastSizeSelected.price, sizeToSend, publicProductData.sizeUnit, publicProductData.id, _lastConfigurableId, engravingCost));
});
string localURI = string.Empty;
if(publicProductData.files.Count > 0 && publicProductData.files.Any(f => f.featuredType == "medium" && f.mediaType == FileMediaType.Image.ToString())) {
FileData fileData = FilesDownloaderManager.instance.filesDownloaderSO.GetFileData(publicProductData.files.Find(f => f.featuredType == "medium" && f.mediaType == FileMediaType.Image.ToString()).fileDataUuid);
if(fileData != null) {
if(fileData.HasDownloaded && fileData.progress > 0.9f) {
localURI = fileData.localURI;
}
if(!fileData.HasDownloaded && fileData.progress > 0f && fileData.progress < 0.9f) {
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded)
localURI = fileData.localURI;
};
} else {
FilesDownloaderManager.instance.CheckAndDownloadAsync(fileData.fileType, fileData.fileExtension, fileData.remoteURI, null, null);
fileData.OnDownloadChange += delegate {
if(fileData.HasDownloaded && fileData.progress > 0.9f)
localURI = fileData.localURI;
};
}
if(!string.IsNullOrEmpty(localURI)) {
if(ImageUtils.CheckForSprite(fileData.localURI)) {
Sprite sprite = ImageUtils.GetPoolSprite(fileData.localURI);
if(sprite != null) {
_materialProductUIHolder.nonMaterialProductImage.sprite = sprite;
}
} else {
Sprite sprite = ImageUtils.LoadNewSprite(localURI);
if(sprite != null)
_materialProductUIHolder.nonMaterialProductImage.sprite = sprite;
}
}
}
}
}
}
}
public void OnOpenMaterialisationPanel() {
_productOverviewButton.interactable = false;
_materialisationButton.interactable = true;
_productOverviewAnimator.SetTrigger("openMaterialisation");
_currentState = ShopUIState.MaterialOverview;
if(_currentMaterialProductDataList != null && _currentMaterialProductDataList.Count > 0) {
_currentMaterialProductId = _currentMaterialProductDataList[0].productId;
// _productOverviewMaterialTypePanel.SetActive(true);
// _productOverviewNonMaterialTypePanel.SetActive(false);
UpdateMaterialPanelUI(true);
} else {
// _productOverviewMaterialTypePanel.SetActive(false);
// _productOverviewNonMaterialTypePanel.SetActive(true);
UpdateMaterialPanelUI(false);
}
if(_lastInstantiatedObject != null && _lastInstantiatedObject?.GetComponent<AssetBundleItemRecognizer>() != null)
_lastInstantiatedObject?.GetComponent<AssetBundleItemRecognizer>().linkedMeshRenderers.ForEach(lm => lm.material = _lastMaterialToSet);
}
public void OnCloseMaterialisationPanel() {
_productOverviewButton.interactable = true;
_materialisationButton.interactable = true;
_currentState = ShopUIState.SliderView;
_productOverviewAnimator.SetTrigger("closeMaterialisation");
}
private void OnAddToCartCallback(CustomEventPasser customEventPasser) {
LoaderUtils.instance.ShowLoader(false, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_materialProductUIHolder.addToCartButton.enabled = true;
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
Debug.Log("OnAddToCartCallback API Error: " + uIGenericEventPasser.message);
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
_materialProductUIHolder.addToCartButton.enabled = true;
} else {
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
DataManager.instance.userConfigurableProductSO.info.lastUserConfigurableProduct = null;
}
}
private void OnCartGetCompleteCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
_materialProductUIHolder.addToCartButton.enabled = true;
} else {
_materialProductUIHolder.addToCartButton.enabled = true;
#region Notifications Hided due to TRI-168 request.
//if(DataManager.instance.userCartSO.info.product.Count > 0) {
//	StatusBarUtility.instance.SetStatus("Cart Fetched Successfully!", StatusType.Info, StatusDelay.NORMAL);
//} else {
//	LoaderUtils.instance.HideLoader();
//	StatusBarUtility.instance.SetStatus("Cart is empty. Please add a product from Shop!", StatusType.Info, StatusDelay.LONG);
//}
#endregion
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.CartScreen));
LoaderUtils.instance.HideLoader();
//LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
//StatusBarUtility.instance.SetStatus("Waiting for all Configurables/Scans Data to download...", StatusType.Info, StatusDelay.LONG);
//EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty));
}
}
public void LoadHomeScene() {
switch(_currentState) {
case ShopUIState.ListView:
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen));
_productSliderSnapper.enabled = true;
break;
case ShopUIState.SliderView:
_currentState = ShopUIState.ListView;
_productSliderSnapper.GoToScreen(0);
_productSliderSnapper.enabled = false;
ClosePublicOverviewPanel();
break;
case ShopUIState.ProductOverview:
_currentState = ShopUIState.SliderView;
_productSliderSnapper.enabled = true;
ToggleProductOverviewPanel(false);
break;
case ShopUIState.MaterialOverview:
_currentState = ShopUIState.SliderView;
_productSliderSnapper.enabled = true;
OnCloseMaterialisationPanel();
break;
default:
_productSliderSnapper.enabled = true;
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.HomeScreen));
break;
}
}
public void ClosePublicOverviewPanel() {
_productOverviewButton.interactable = true;
_materialisationButton.interactable = true;
_productSliderSnapper.enabled = true;
_currentState = ShopUIState.ListView;
_productOverviewMaterialTypePanel.SetActive(true);
_productOverviewNonMaterialTypePanel.SetActive(false);
_productOverviewPanel.SetActive(false);
}
public void ToggleProductOverviewPanel(bool toggle) {
if(toggle) {
_productOverviewAnimator.SetTrigger("openProductOverview");
_currentState = ShopUIState.ProductOverview;
_productSliderSnapper.enabled = false;
_productOverviewButton.interactable = true;
_materialisationButton.interactable = false;
} else {
_productSliderSnapper.enabled = true;
_productOverviewAnimator.SetTrigger("closeProductOverview");
_currentState = ShopUIState.SliderView;
_productOverviewButton.interactable = true;
_materialisationButton.interactable = true;
}
}
#endregion
}
[Serializable]
public class MaterialProductUIHolder {
public TMP_Text materialTitleText;
public TMP_Text materialDescriptionText;
public TMP_Text materialSizeText;
public TMP_Text materialPriceText;
public Button decreaseQuantity;
public Button increaseQuantity;
public TMPro.TMP_InputField quantityInput;
public Button addToCartButton;
public Image nonMaterialProductImage;
public GameObject assetBundlePrefabContainer;
public int quantitySet = 1;
public void CleanHolder() {
materialTitleText.text = string.Empty;
materialDescriptionText.text = string.Empty;
materialSizeText.text = string.Empty;
materialPriceText.text = string.Empty;
nonMaterialProductImage.gameObject.SetActive(false);
quantityInput.text = "1";
quantitySet = 1;
decreaseQuantity.onClick.RemoveAllListeners();
increaseQuantity.onClick.RemoveAllListeners();
quantityInput.onEndEdit.RemoveAllListeners();
}
}
[Serializable]
public enum ShopUIState {
ListView,
SliderView,
ProductOverview,
MaterialOverview
}
[Serializable]
public class ProductSliderSet {
public ProductAssetType assetType;
public List<Sprite> sliderSprites;
}
}

6. Order Creation UI Controller

This is the crux of order creation for the e-commerce part of the game. From the global cart of the logged in user, order creation can be proceeded where the usual fields such as Billing Address, Shipping Address, Offers Selection and Payment Options are setup.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using Hotchform.Game.Triumph.DataHandlers.Scriptables;
using Hotchform.Game.Triumph.Managers;
using Hotchform.Game.Triumph.Utilities.Mono;
using UnityEngine;
//using UnityEngine.Analytics;
using UnityEngine.Events;
using UnityEngine.UI;
/*===============================================================
Product:    TRIUMPH
Developer:  Ankit Sethi - [email protected]
Company:    Triumph by hochform GmbH
Date:       24/08/2018 14:35
Copyright:  Copyright @ Triumph by hochform GmbH 2018-2019
================================================================*/
using System.Runtime.CompilerServices;
using Hotchform.Game.Triumph.API.DataModels;
using TMPro;
using Hotchform.Game.Triumph.Utilities;
using System.Linq;
namespace Hotchform.Game.Triumph.Controllers {
public class OrderCreationUIController : MonoBehaviour {
#region Public Variables.
#endregion
#region Private Variables.
[SerializeField] private OrderCreationUIState _currentState;
[SerializeField] private TMPro.TMP_Text _finalOrderPriceText;
[SerializeField] private Button _createOrderButton;
[SerializeField] private Button _payTabButton;
[SerializeField] private GameObject _billingAddressButton;
[SerializeField] private TMPro.TMP_Dropdown _offersDropdown;
[SerializeField] private TMPro.TMP_Text _selectedOfferText;
[SerializeField] private GameObject _selectedDiscountContainer;
[SerializeField] private TMPro.TMP_Text _selectedDiscountText;
[SerializeField] private UnityEvent _onShippingAddressTabClickEvent;
[SerializeField] private UnityEvent _onBillingAddressTabClickEvent;
[SerializeField] private UnityEvent _onPayAddressTabClickEvent;
[SerializeField] private BillingAddressData _billingAddressData;
[SerializeField] private DeliveryAddressData _deliveryAddressData;
[SerializeField] private Animator _orderTabAnimator;
[SerializeField] private Image _shippingTabUnderlineImage;
[SerializeField] private TMPro.TMP_Text _orderButtonText;
private bool canCreateOrder;
private float _lastPaymentTotalPrice;
private string _lastPaymentID;
private bool _paymentTypeSelected = true;
private string _lastSelectedCouponCode;
#endregion
#region Unity Methods.
// Use this for initialization
void Start() {
_currentState = OrderCreationUIState.ShippingTab;
//_orderTabAnimator.SetTrigger("activate");
_orderButtonText.text = "weiter zur Zahlung";
_offersDropdown.value = -1;
//_billingAddressButton.SetActive(true);
_selectedDiscountContainer.SetActive(false);
_selectedOfferText.gameObject.SetActive(false);
SetupOffers();
//Setup Order from last cart.
SetupOrderFromCart();
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
//_payTabButton.interactable = false;
// _payTabButton.onClick.AddListener(() => {
// 	_currentState = OrderCreationUIState.PaymentTab;
// 	if(_paymentTypeSelected)
// 		_createOrderButton.interactable = true;
// 	else
// 		_createOrderButton.interactable = false;
// 	_orderButtonText.text = "verbindlich bestellen";
// 	_onPayAddressTabClickEvent?.Invoke();
// });
_createOrderButton.onClick.AddListener(() => {
switch(_currentState) {
case OrderCreationUIState.ShippingTab:
OnPayAddressTabClick();
break;
case OrderCreationUIState.BillingTab:
OnPayAddressTabClick();
break;
case OrderCreationUIState.PaymentTab:
if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.copounCode))
DataManager.instance.userOrdersSO.info.tempOrder.copounCode = "NoCoupon";
//if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.pay.couponcode))
//DataManager.instance.userOrdersSO.info.tempOrder.pay.couponcode = "NoCoupon";
if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.pay.paymentId)) {
OnDoPaypalPayment();
} else {
_createOrderButton.interactable = false;
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
EventManager.TriggerEvent(EventName.DB_OrderCreateForLoggedInUser, new CustomEventPasser());
}
break;
default:
break;
}
});
}
private void OnEnable() {
EventManager.StartListening(EventName.UI_ApplyCouponToCartComplete, OnApplyCouponCallback);
EventManager.StartListening(EventName.UI_OrderCreateForLoggedInUserComplete, OnOrderCreateCallback);
EventManager.StartListening(EventName.UI_ConfirmPaypalPaymentComplete, OnConfirmPaypalPaymentCallback);
EventManager.StartListening(EventName.UI_GetPaypalURLLoggedInUserComplete, OnGetPaypalURLCallback);
EventManager.StartListening(EventName.UI_LoggedInUserCartGetComplete, OnCartGetCompleteCallback);
}
private void OnDisable() {
EventManager.StopListening(EventName.UI_ApplyCouponToCartComplete, OnApplyCouponCallback);
EventManager.StopListening(EventName.UI_OrderCreateForLoggedInUserComplete, OnOrderCreateCallback);
EventManager.StopListening(EventName.UI_ConfirmPaypalPaymentComplete, OnConfirmPaypalPaymentCallback);
EventManager.StopListening(EventName.UI_GetPaypalURLLoggedInUserComplete, OnGetPaypalURLCallback);
EventManager.StopListening(EventName.UI_LoggedInUserCartGetComplete, OnCartGetCompleteCallback);
}
#endregion
#region UI Input Receiver Methods.
public void SetShippingFirstName(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.firstName = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetShippingLastName(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.lastName = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetShippingStreet(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.street = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetShippingArea(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.place = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetShippingPincode(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.pincode = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
var billAddress = DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress;
if(billAddress != null && !string.IsNullOrEmpty(billAddress.firstName) && !string.IsNullOrEmpty(billAddress.lastName) && !string.IsNullOrEmpty(billAddress.place) && !string.IsNullOrEmpty(billAddress.street) && !string.IsNullOrEmpty(billAddress.pincode)) {
_payTabButton.interactable = true;
}
}
public void SetOrderComment(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.orderComment = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void OnRememberOrderValueChange(bool check) {
//DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress.re = input;
//TODO
// if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.pay.paymentId))
// 	_createOrderButton.interactable = false;
// else
// 	_createOrderButton.interactable = true;
}
public void OnSameAddressConfirmValueChange(bool check) {
//_shippingTabUnderlineImage.enabled = true;
_orderTabAnimator.enabled = true;
if(!check)
_orderTabAnimator.SetTrigger("deActivate");
else
_orderTabAnimator.SetTrigger("activate");
DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddressSame = !check;
if(check) {
var shippingAddress = DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress;
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress = new DataHandlers.Scriptables.OrderBillAddress {
firstName = shippingAddress.firstName,
lastName = shippingAddress.lastName,
pincode = shippingAddress.pincode,
place = shippingAddress.place,
street = shippingAddress.street
};
}
//_billingAddressButton.SetActive(check);
_payTabButton.interactable = true;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void OnShippingAddressTabClick() {
_currentState = OrderCreationUIState.ShippingTab;
_orderTabAnimator.enabled = false;
_orderButtonText.text = "weiter zur Zahlung";
//_shippingTabUnderlineImage.enabled = true;
_onShippingAddressTabClickEvent?.Invoke();
}
public void OnBillingAddressTabClick() {
_currentState = OrderCreationUIState.BillingTab;
_orderButtonText.text = "weiter zur Zahlung";
//_shippingTabUnderlineImage.enabled = true;
_orderTabAnimator.enabled = true;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
var shippingAddress = DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddress;
if(string.IsNullOrEmpty(shippingAddress.firstName))
StatusBarUtility.instance.SetStatus(GameConstants.validFirstNameWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(shippingAddress.lastName))
StatusBarUtility.instance.SetStatus(GameConstants.validLastNameWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(shippingAddress.pincode))
StatusBarUtility.instance.SetStatus(GameConstants.validPincodeAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(shippingAddress.place))
StatusBarUtility.instance.SetStatus(GameConstants.validAreaAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(shippingAddress.street))
StatusBarUtility.instance.SetStatus(GameConstants.validStreetAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else {
//if(DataManager.instance.userOrdersSO.info.tempOrder.address.shippingAddressSame)
//	_onPayAddressTabClickEvent?.Invoke();
//else
//_onBillingAddressTabClickEvent?.Invoke();
_onBillingAddressTabClickEvent?.Invoke();
}
}
public void SetBillingFirstName(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress.firstName = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetBillingLastName(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress.lastName = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetBillingStreet(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress.street = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetBillingArea(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress.place = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void SetBillingPincode(string input) {
DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress.pincode = input;
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
}
public void OnPayAddressTabClick() {
_currentState = OrderCreationUIState.PaymentTab;
_orderTabAnimator.enabled = false;
//if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.pay.paymentId))
//	_createOrderButton.interactable = false;
//else
//_createOrderButton.interactable = true;
_orderButtonText.text = "verbindlich bestellen";
if(_paymentTypeSelected)
_createOrderButton.interactable = true;
else
_createOrderButton.interactable = false;
var billingAddress = DataManager.instance.userOrdersSO.info.tempOrder.address.billAddress;
if(string.IsNullOrEmpty(billingAddress.firstName))
StatusBarUtility.instance.SetStatus(GameConstants.validFirstNameWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(billingAddress.lastName))
StatusBarUtility.instance.SetStatus(GameConstants.validLastNameWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(billingAddress.pincode))
StatusBarUtility.instance.SetStatus(GameConstants.validPincodeAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(billingAddress.place))
StatusBarUtility.instance.SetStatus(GameConstants.validAreaAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else if(string.IsNullOrEmpty(billingAddress.street))
StatusBarUtility.instance.SetStatus(GameConstants.validStreetAddressWarning, StatusType.Warning, StatusDelay.NORMAL);
else
_onPayAddressTabClickEvent?.Invoke();
}
public void OnPaymentTypeSelected() {
_paymentTypeSelected = true;
_createOrderButton.gameObject.SetActive(true);
_createOrderButton.interactable = true;
_orderButtonText.text = "verbindlich bestellen";
}
public void SetPayLegalName(string input) {
//DataManager.instance.userOrdersSO.info.tempOrder.pay.name = input;
//_createOrderButton.interactable = false;
}
public void SetPayCardNumber(string input) {
//long.TryParse(input, out long result);
//DataManager.instance.userOrdersSO.info.tempOrder.pay.accountno = result;
//_createOrderButton.interactable = false;
}
public void SetPayExpiryMonth(int option) {
//DataManager.instance.userOrdersSO.info.tempOrder.pay.expMonth = option == 0 ? "01" : (1 + option).ToString("D2");
//_createOrderButton.interactable = false;
}
public void SetPayExpiryYear(int option) {
//DataManager.instance.userOrdersSO.info.tempOrder.pay.expYear = option == 0 ? "2018" : (2018 + option).ToString();
//_createOrderButton.interactable = false;
}
public void SetPaySecurityCode(string code) {
//DataManager.instance.userOrdersSO.info.tempOrder.pay.securitycode = code;
//CheckPayData();
}
public void SetPayRemember(bool option) {
DataManager.instance.userOrdersSO.info.tempOrder.pay.remember = option;
}
public void SetPayCouponCode(string input) {
//DataManager.instance.userOrdersSO.info.tempOrder.pay.couponcode = string.IsNullOrEmpty(input) ? "NoCoupon" : input;
}
#endregion
#region Custom Methods.
private void SetupOffers() {
var offersData = DataManager.instance.userOffersSO.info.offers.Where(o => !o.isUsed).ToList();
if(offersData.Count > 0 && offersData.Any(o => !o.isUsed)) {
_offersDropdown.interactable = true;
_offersDropdown.ClearOptions();
List<TMPro.TMP_Dropdown.OptionData> offersOptions = new List<TMPro.TMP_Dropdown.OptionData>();
for(int i = 0; i < offersData.Count; i++) {
if(!offersData[i].isUsed) {
TMP_Dropdown.OptionData optionData = new TMPro.TMP_Dropdown.OptionData {
text = offersData[i].copoun_code + " / " + (offersData[i].discountType == DiscountType.percentage.ToString() ? offersData[i].percentage + "%" : DataManager.instance.userCartSO.info.cartCurrency + " " + offersData[i].discountAmount.ToString())
};
offersOptions.Add(optionData);
}
}
_offersDropdown.AddOptions(offersOptions);
_offersDropdown.onValueChanged.RemoveAllListeners();
_offersDropdown.onValueChanged.AddListener(delegate {
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_lastSelectedCouponCode = offersData[_offersDropdown.value].copoun_code;
EventManager.TriggerEvent(EventName.DB_ApplyCouponToCart, new DBApplyCouponEventPasser(offersData[_offersDropdown.value].copoun_code, ApplyCouponAction.apply));
});
} else {
_offersDropdown.interactable = false;
}
}
public void SetOfferOption(int value) {
var offersData = DataManager.instance.userOffersSO.info.offers.Where(o => !o.isUsed).ToList();
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
_lastSelectedCouponCode = offersData[value].copoun_code;
EventManager.TriggerEvent(EventName.DB_ApplyCouponToCart, new DBApplyCouponEventPasser(offersData[_offersDropdown.value].copoun_code, ApplyCouponAction.apply));
}
private void SetupOrderFromCart() {
var cartData = DataManager.instance.userCartSO.info;
var myAccountData = DataManager.instance.usersDataSO.GetUserDataOfUser(DataManager.instance.usersDataSO.info.currentLoggedInUserSettings.uuid).accountData;
_billingAddressData.addressInput.text = myAccountData.address.billAddress.street;
_billingAddressData.addressInput.onEndEdit.RemoveAllListeners();
_billingAddressData.addressInput.onEndEdit.AddListener(SetBillingStreet);
_billingAddressData.placeInput.text = myAccountData.address.billAddress.place;
_billingAddressData.placeInput.onEndEdit.RemoveAllListeners();
_billingAddressData.placeInput.onEndEdit.AddListener(SetBillingArea);
_billingAddressData.pincodeInput.text = myAccountData.address.billAddress.pincode;
_billingAddressData.pincodeInput.onEndEdit.RemoveAllListeners();
_billingAddressData.pincodeInput.onEndEdit.AddListener(SetBillingPincode);
_billingAddressData.firstNameInput.text = myAccountData.address.billAddress.firstName;
_billingAddressData.firstNameInput.onEndEdit.RemoveAllListeners();
_billingAddressData.firstNameInput.onEndEdit.AddListener(SetBillingFirstName);
_billingAddressData.lastNameInput.text = myAccountData.address.billAddress.lastName;
_billingAddressData.lastNameInput.onEndEdit.RemoveAllListeners();
_billingAddressData.lastNameInput.onEndEdit.AddListener(SetBillingLastName);
_deliveryAddressData.addressInput.text = myAccountData.address.shippingAddress.street;
_deliveryAddressData.addressInput.onEndEdit.RemoveAllListeners();
_deliveryAddressData.addressInput.onEndEdit.AddListener(SetShippingStreet);
_deliveryAddressData.placeInput.text = myAccountData.address.shippingAddress.place;
_deliveryAddressData.placeInput.onEndEdit.RemoveAllListeners();
_deliveryAddressData.placeInput.onEndEdit.AddListener(SetShippingArea);
_deliveryAddressData.pincodeInput.text = myAccountData.address.shippingAddress.pincode;
_deliveryAddressData.pincodeInput.onEndEdit.RemoveAllListeners();
_deliveryAddressData.pincodeInput.onEndEdit.AddListener(SetShippingPincode);
_deliveryAddressData.firstNameInput.text = myAccountData.address.shippingAddress.firstName;
_deliveryAddressData.firstNameInput.onEndEdit.RemoveAllListeners();
_deliveryAddressData.firstNameInput.onEndEdit.AddListener(SetShippingFirstName);
_deliveryAddressData.lastNameInput.text = myAccountData.address.shippingAddress.lastName;
_deliveryAddressData.lastNameInput.onEndEdit.RemoveAllListeners();
_deliveryAddressData.lastNameInput.onEndEdit.AddListener(SetShippingLastName);
var tempOrder = DataManager.instance.userOrdersSO.info.tempOrder;
tempOrder = new UserOrderData {
address = new OrderAddress()
};
tempOrder.address.billAddress = new OrderBillAddress {
firstName = myAccountData.address.billAddress.firstName,
lastName = myAccountData.address.billAddress.lastName,
place = string.IsNullOrEmpty(myAccountData.address.billAddress.place) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.city : myAccountData.address.billAddress.place,
street = string.IsNullOrEmpty(myAccountData.address.billAddress.street) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.region_name : myAccountData.address.billAddress.street,
pincode = string.IsNullOrEmpty(myAccountData.address.billAddress.pincode) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.zip : myAccountData.address.billAddress.pincode
};
tempOrder.address.shippingAddress = new OrderShippingAddress {
firstName = myAccountData.address.shippingAddress.firstName,
lastName = myAccountData.address.shippingAddress.lastName,
place = string.IsNullOrEmpty(myAccountData.address.shippingAddress.place) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.city : myAccountData.address.shippingAddress.place,
street = string.IsNullOrEmpty(myAccountData.address.shippingAddress.street) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.region_name : myAccountData.address.shippingAddress.street,
pincode = string.IsNullOrEmpty(myAccountData.address.shippingAddress.pincode) ? DataManager.instance.tempDataSO.info.lastGeolocationAddress.zip : myAccountData.address.shippingAddress.pincode
};
tempOrder.address.shippingAddressSame = myAccountData.address.shippingAddressSame;
tempOrder.ipaddress = DataManager.instance.tempDataSO.info.lastGeolocationAddress.ip;
tempOrder.deviceId = SystemInfo.deviceUniqueIdentifier;
tempOrder.orderStatus = nameof(OrderStatus.inprogress);
tempOrder.orderType = nameof(OrderType.prepaid);
tempOrder.orderComment = "No Order Comment";
tempOrder.copounCode = string.IsNullOrEmpty(cartData.cartCoupon) ? "nocopoun" : cartData.cartCoupon;
tempOrder.priceCurrency = cartData.cartCurrency;
tempOrder.orderFinalPrice = cartData.cartFinalPrice;
tempOrder.orderDiscountAmount = cartData.discountAmount;
tempOrder.calculatePrice = new OrderCalculatePrice {
cartSubtotal = cartData.calculatePrice.cartSubtotal,
totalShiping = cartData.calculatePrice.totalShiping,
totaltax = cartData.calculatePrice.totaltax
};
_finalOrderPriceText.text = "€ " + tempOrder.orderFinalPrice.ToString("F2", DateUtils.GermanCulture);
tempOrder.product = new List<OrderProduct>();
foreach(var item in cartData.product) {
var orderProduct = new OrderProduct {
id = item.id,
lang_type = item.lang_type,
title = item.title,
quantity = item.quantity,
price = item.price,
product_id = item.product_id,
size = item.size,
sizeUnit = item.sizeUnit,
user_configure_product_id = item.user_configure_product_id
};
orderProduct.files = new List<OrderProductFile>();
foreach(var fileItem in item.files) {
var productFile = new OrderProductFile {
createdAt = fileItem.createdAt,
updatedAt = fileItem.updatedAt,
mediaType = fileItem.mediaType,
mediaFormat = fileItem.mediaFormat,
platformType = fileItem.platformType,
mediaUrl = fileItem.mediaUrl,
featuredType = fileItem.featuredType
};
orderProduct.files.Add(productFile);
}
tempOrder.product.Add(orderProduct);
}
tempOrder.pay = new OrderPay {
name = myAccountData.firstName + " " + myAccountData.lastName,
remember = true,
mode = "paypal"
};
DataManager.instance.userOrdersSO.info.tempOrder = tempOrder;
}
private bool CheckPayData() {
bool check = false;
//_createOrderButton.interactable = true;
//var data = DataManager.instance.userOrdersSO.info.tempOrder.pay;
//if(string.IsNullOrEmpty(data.name))
//	StatusBarUtility.instance.SetStatus("Empty Name for Card Payment is not allowed. Please fill to proceed!");
//else if(string.IsNullOrEmpty(data.securitycode))
//	StatusBarUtility.instance.SetStatus("Empty Name for Card Payment is not allowed. Please fill to proceed!");
//else if(string.IsNullOrEmpty(data.accountno.ToString()))
//	StatusBarUtility.instance.SetStatus("Empty Name for Card Payment is not allowed. Please fill to proceed!");
////else if(data.accountno.ToString().Length < 16)
////    StatusBarUtility.instance.SetStatus("Card Number with less than 16 digits is not allowed. Please try again!");
//else
//	_createOrderButton.interactable = true;
////TODO: Remove in production.
//_createOrderButton.interactable = true;
return check;
}
public void OnDoPaypalPayment() {
LoaderUtils.instance.ShowLoader();
_lastPaymentTotalPrice = DataManager.instance.userOrdersSO.info.tempOrder.calculatePrice.cartSubtotal;
EventManager.TriggerEvent(EventName.DB_GetPaypalURLComplete, new CustomEventPasser());
}
#endregion
#region Callback Methods.
private void OnApplyCouponCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
//#region Notifications Hided due to TRI-168 request.
StatusBarUtility.instance.SetStatus(GameConstants.offerApplySuccessInfo, StatusType.Info, StatusDelay.NORMAL);
//#endregion
if(!string.IsNullOrEmpty(_lastSelectedCouponCode)) {
DataManager.instance.userOrdersSO.info.tempOrder.copounCode = _lastSelectedCouponCode;
_offersDropdown.gameObject.SetActive(false);
_selectedOfferText.gameObject.SetActive(true);
var selectedOfferData = DataManager.instance.userOffersSO.info.offers.Find(o => o.copoun_code == _lastSelectedCouponCode);
_selectedOfferText.gameObject.SetActive(true);
_selectedOfferText.text = selectedOfferData.copoun_code + " / " + (selectedOfferData.discountType == DiscountType.percentage.ToString() ? selectedOfferData.percentage + "%" : DataManager.instance.userCartSO.info.cartCurrency + " " + selectedOfferData.discountAmount.ToString());
_selectedDiscountContainer.gameObject.SetActive(true);
_selectedDiscountText.text = selectedOfferData.discountType == DiscountType.percentage.ToString() ? "-" + selectedOfferData.percentage + "%" : "-" + selectedOfferData.discountAmount.ToString();
}
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
}
}
private void OnCartGetCompleteCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
#region Notifications Hided due to TRI-168 request.
//if(DataManager.instance.userCartSO.info.product.Count > 0) {
//	StatusBarUtility.instance.SetStatus("Cart Fetched Successfully!", StatusType.Info, StatusDelay.NORMAL);
//} else {
//	LoaderUtils.instance.HideLoader();
//	StatusBarUtility.instance.SetStatus("Cart is empty. Please add a product from Shop!", StatusType.Info, StatusDelay.LONG);
//}
#endregion
SetupOffers();
SetupOrderFromCart();
LoaderUtils.instance.HideLoader();
//LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
//StatusBarUtility.instance.SetStatus("Waiting for all Configurables/Scans Data to download...", StatusType.Info, StatusDelay.LONG);
//EventManager.TriggerEvent(EventName.DB_GetAllConfigurables, new DBUserConfigurableLastEvaluatedEventPasser(string.Empty, string.Empty));
}
}
private void OnOrderCreateCallback(CustomEventPasser customEventPasser) {
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
_createOrderButton.interactable = true;
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
#region Notifications Hided due to TRI-168 request.
//StatusBarUtility.instance.SetStatus("Order Created Successfully!", StatusType.Info, StatusDelay.NORMAL);
#endregion
//EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
//Analytics.CustomEvent("Order Created", new Dictionary<string, object> {
//	{ "username", DataManager.instance.GetCurrentLoggedInAccountData().username },
//	{ "orderJson", JsonUtility.ToJson(DataManager.instance.userOrdersSO.info.tempOrder) },
//	{ "dateTime", DateTime.Now.ToString("ddMMyyyy_hhMMss") }
//});
DataManager.instance.userOrdersSO.info.tempOrder = null;
DataManager.instance.userCartSO.info = null;
EventManager.TriggerEvent(EventName.DB_GetLoggedInUserCart, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOffersForLoggedInUser, new CustomEventPasser());
EventManager.TriggerEvent(EventName.DB_GetAllOrdersForLoggedInUser, new DBGetAllOrdersEventPasser(false, string.Empty));
EventManager.TriggerEvent(EventName.SM_LoadScene, new CustomLoadSceneEventPasser(CustomScene.OrderResponseScreen));
}
LoaderUtils.instance.HideLoader();
}
private void OnGetPaypalURLCallback(CustomEventPasser customEventPasser) {
_createOrderButton.interactable = false;
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
} else {
//StatusBarUtility.instance.SetStatus("Order Created Successfully!", StatusType.Info, StatusDelay.NORMAL);
if(Application.isMobilePlatform) {
InAppBrowser.DisplayOptions options = new InAppBrowser.DisplayOptions {
displayURLAsPageTitle = false,
pageTitle = "Payment Gateway"
};
InAppBrowser.ClearCache();
InAppBrowser.OpenURL(uIGenericEventPasser.message, options);
InAppBrowserBridge appBrowserBridge = FindObjectOfType<InAppBrowserBridge>();
appBrowserBridge.onBrowserFinishedLoading.AddListener(url => {
if(url.Contains("success.html")) {
// Breaking payment url;
string paymentData = url.Split('?')[1];
string[] paymentDetails = paymentData.Split('&');
string payerId = string.Empty;
_lastPaymentID = "TestPaymentID";
foreach(var item in paymentDetails) {
if(item.StartsWith("paymentId", StringComparison.InvariantCultureIgnoreCase)) {
_lastPaymentID = item.Split('=')[1];
}
if(item.StartsWith("PayerID", StringComparison.InvariantCultureIgnoreCase)) {
payerId = item.Split('=')[1];
}
}
//Debug.Log("Last Payment ID: " + _lastPaymentID);
DataManager.instance.userOrdersSO.info.tempOrder.pay.paymentId = _lastPaymentID;
EventManager.TriggerEvent(EventName.DB_ConfirmPaypalPaymentComplete, new DBPaypalConfirmEventPasser(payerId, _lastPaymentID, _lastPaymentTotalPrice));
_lastPaymentTotalPrice = 0f;
} else {
_createOrderButton.interactable = true;
LoaderUtils.instance.HideLoader();
}
if(url.Contains("cancel.html")) {
_createOrderButton.interactable = true;
InAppBrowser.CloseBrowser();
LoaderUtils.instance.HideLoader();
StatusBarUtility.instance.SetStatus(GameConstants.paymentCancelledByUserInfo, StatusType.Warning, StatusDelay.LONG);
} else {
_createOrderButton.interactable = true;
LoaderUtils.instance.HideLoader();
}
});
// appBrowserBridge.onBrowserFinishedLoadingWithError.AddListener((url, error) => {
// 	_createOrderButton.interactable = false;
// 	InAppBrowser.CloseBrowser();
// 	StatusBarUtility.instance.SetStatus(GameConstants.paymentPortalProblemWarning, StatusType.Warning, StatusDelay.VERY_LONG);
// 	if(url.Contains("success.html")) {
// 		// Breaking payment url;
// 		string paymentData = url.Split('?')[1];
// 		string[] paymentDetails = paymentData.Split('&');
// 		string payerId = string.Empty;
// 		_lastPaymentID = "TestPaymentID";
// 		foreach(var item in paymentDetails) {
// 			if(item.StartsWith("paymentId", StringComparison.InvariantCultureIgnoreCase)) {
// 				_lastPaymentID = item.Split('=')[1];
// 			}
// 			if(item.StartsWith("PayerID", StringComparison.InvariantCultureIgnoreCase)) {
// 				payerId = item.Split('=')[1];
// 			}
// 		}
// 		//Debug.Log("Last Payment ID: " + _lastPaymentID);
// 		DataManager.instance.userOrdersSO.info.tempOrder.pay.paymentId = _lastPaymentID;
// 		EventManager.TriggerEvent(EventName.DB_ConfirmPaypalPaymentComplete, new DBPaypalConfirmEventPasser(payerId, _lastPaymentID, _lastPaymentTotalPrice));
// 		_lastPaymentTotalPrice = 0f;
// 	} else {
// 		_createOrderButton.interactable = true;
// 		LoaderUtils.instance.HideLoader();
// 	}
// 	if(url.Contains("cancel.html")) {
// 		_createOrderButton.interactable = true;
// 		InAppBrowser.CloseBrowser();
// 		LoaderUtils.instance.HideLoader();
// 		StatusBarUtility.instance.SetStatus(GameConstants.paymentCancelledByUserInfo, StatusType.Warning, StatusDelay.LONG);
// 	} else {
// 		_createOrderButton.interactable = true;
// 		LoaderUtils.instance.HideLoader();
// 	}
// });
appBrowserBridge.onBrowserClosed.AddListener(() => {
LoaderUtils.instance.HideLoader();
_createOrderButton.interactable = true;
});
}
}
}
private void OnConfirmPaypalPaymentCallback(CustomEventPasser customEventPasser) {
InAppBrowser.CloseBrowser();
UIGenericEventPasser uIGenericEventPasser = (UIGenericEventPasser)customEventPasser;
if(uIGenericEventPasser.isError || uIGenericEventPasser.isFailure) {
_createOrderButton.interactable = false;
StatusBarUtility.instance.SetStatus(GameConstants.genericServerError, StatusType.Error, StatusDelay.LONG);
LoaderUtils.instance.HideLoader();
} else {
ConfirmPaypalPaymentResponseBody message = JsonUtility.FromJson<ConfirmPaypalPaymentResponseBody>(uIGenericEventPasser.message);
DataManager.instance.userOrdersSO.info.tempOrder.orderStatus = "completed";
canCreateOrder = true;
_createOrderButton.interactable = true;
#region Notifications Hided due to TRI-168 request.
//StatusBarUtility.instance.SetStatus("Paypal Payment Confirmed with status: " + message.payer.status, StatusType.Info, StatusDelay.LONG);
#endregion
_lastPaymentID = "TestPayementID";
_lastPaymentTotalPrice = 0f;
if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.copounCode))
DataManager.instance.userOrdersSO.info.tempOrder.copounCode = "NoCoupon";
//if(string.IsNullOrEmpty(DataManager.instance.userOrdersSO.info.tempOrder.pay.couponcode))
//DataManager.instance.userOrdersSO.info.tempOrder.pay.couponcode = "NoCoupon";
_createOrderButton.interactable = false;
LoaderUtils.instance.ShowLoader(true, LoaderSizeType.Normal, LoaderVerticalAlignment.Center);
EventManager.TriggerEvent(EventName.DB_OrderCreateForLoggedInUser, new CustomEventPasser());
}
}
#endregion
}
[Serializable]
public enum OrderCreationUIState {
ShippingTab,
BillingTab,
PaymentTab
}
}