Untitled

mail@pastecode.io avatar
unknown
csharp
a month ago
7.8 kB
2
Indexable
Never
using System;
using System.Threading;
using Common.Controllers.Extensions;
using Features.InApps.Public.Data.Triggers;
using Features.InApps.Public.Services;
using Common.Loader.Controllers;
using Common.Loader.Payloads;
using Common.LocalizationConstants;
using Common.Payments.Controllers;
using Common.Payments.Data;
using Common.Payments.Data.Purchase;
using Common.Payments.Facades;
using Common.Repository.Infrastructure;
using Common.SaveNotifier.Infrastructure;
using Common.StateMachine.State;
using Common.UI;
using Cysharp.Threading.Tasks;
using Features.InApps.Public.Providers;
using Features.Piggy.Internal.Data.PiggyPopup;
using Features.Piggy.Public.Data;
using Features.WinStreak.Public.Notifiers;
using Playtika.Unity.ControllerTree;
using Playtika.Unity.ControllerTree.StateMachine;
using SGH.Controllers.ViewHolder.Infrastructure;
using Tools.LocalizationTools;
using UnityEngine;
using Zenject;
using ZLogger;

namespace Features.Piggy.Internal.States.PiggyPopup.InternalStates
{
	internal class PiggyPopupPurchaseState : State
	{
		private const float DebugDelayInEditor = 1.5f;

		private readonly IRepository<PiggyProgressData> _piggyProgressRepository;
		private readonly IFactory<PiggyPopupRewardState> _piggyPopupRewardStateFactory;
		private readonly IFactory<ElasticLoaderController> _loaderControllerFactory;
		private readonly IFactory<PaymentsResultPopupsController> _paymentResultPopupControllerFactory;
		private readonly IPaymentsFacade _paymentsFacade;
		private readonly IRequestSaveNotifier _requestSaveNotifier;
		private readonly PiggyPopupStateData _piggyPopupStateData;
		private readonly OverlayCanvas _overlayCanvas;
		private readonly IInAppsRefreshService _inAppsRefreshService;
		private readonly IInAppsService _inAppsService;
		private readonly IInAppsConditionalTriggerProvider _conditionalTriggerProvider;
		private readonly IActiveInAppsService _activeInAppsService;
		private readonly IWinStreakRewardNotifier _winStreakRewardNotifier;

		private ElasticLoaderController _loaderController;
		private CancellationTokenSource _inAppsCancellationTokenSource;

		public PiggyPopupPurchaseState(
			IRepository<PiggyProgressData> piggyProgressRepository,
			IFactory<PiggyPopupRewardState> piggyPopupRewardStateFactory,
			IFactory<ElasticLoaderController> loaderControllerFactory,
			IFactory<PaymentsResultPopupsController> paymentResultPopupControllerFactory,
			IPaymentsFacade paymentFacade,
			IRequestSaveNotifier requestSaveNotifier,
			IObjectHolderAcrossControllersChildren<PiggyPopupStateData> piggyPopupStateDataHolder,
			OverlayCanvas overlayCanvas,
			IInAppsRefreshService inAppsRefreshService,
			IInAppsService inAppsService,
			IInAppsConditionalTriggerProvider conditionalTriggerProvider,
			IActiveInAppsService activeInAppsService,
			IWinStreakRewardNotifier winStreakRewardNotifier
		)
		{
			_piggyProgressRepository = piggyProgressRepository;
			_piggyPopupRewardStateFactory = piggyPopupRewardStateFactory;
			_loaderControllerFactory = loaderControllerFactory;
			_paymentResultPopupControllerFactory = paymentResultPopupControllerFactory;
			_paymentsFacade = paymentFacade;
			_requestSaveNotifier = requestSaveNotifier;
			_piggyPopupStateData = piggyPopupStateDataHolder.CurrentValue;
			_overlayCanvas = overlayCanvas;
			_inAppsRefreshService = inAppsRefreshService;
			_inAppsService = inAppsService;
			_conditionalTriggerProvider = conditionalTriggerProvider;
			_activeInAppsService = activeInAppsService;
			_winStreakRewardNotifier = winStreakRewardNotifier;
		}

		protected override UniTask OnInitialize(CancellationToken token)
		{
			_inAppsCancellationTokenSource = new CancellationTokenSource();

			Resources.Attach(_inAppsCancellationTokenSource);

			return UniTask.CompletedTask;
		}

		protected override async UniTask<IStackedControllerInfo> RunningForResult(CancellationToken token)
		{
			RemoveFinishedInApps();
			RequestAvailableInApps();

			await PurchasePiggy(token);

			return await base.RunningForResult(token);
		}

		private async UniTask PurchasePiggy(CancellationToken token)
		{
			await ShowLoader(token);

			var purchaseSourceData = GetPurchaseSourceData();

			var result = await _paymentsFacade.PurchaseShopProduct(_piggyPopupStateData.ProductData.Product, purchaseSourceData, token);

			if (Application.isEditor)
			{
				await UniTask.Delay(TimeSpan.FromSeconds(DebugDelayInEditor), cancellationToken: token);
			}

			HideLoader();

			await ProcessPurchasingResult(result, token);
		}

		private async UniTask ShowLoader(CancellationToken token)
		{
			var parent = _overlayCanvas.transform;
			var text = await Localization.CommonTerms.Loader_Purchasing.GetTranslation(token);

			var loaderPayload = ElasticLoaderPayload.Loading(parent, text);

			_loaderController = await Children.Run(_loaderControllerFactory, loaderPayload, token: token);
		}

		private void HideLoader()
		{
			_loaderController.TryStop().Forget();
		}

		private PurchaseSourceData GetPurchaseSourceData()
		{
			var appearanceId = _piggyProgressRepository.Get().AppearanceId;

			return new PurchaseSourceData(PurchaseSourceType.PIGGY_POPUP, appearanceId);
		}

		private async UniTask ProcessPurchasingResult(PurchasingResultDescription resultDescription, CancellationToken token)
		{
			if (resultDescription.Result == PurchasingResult.Rewarded)
			{
				RemovePeggyExitInApps();
				await ConsumeShopProduct(resultDescription, token);
				ProcessWinStreakRewards();
				_requestSaveNotifier.RequestSaveAndPushSyncService();
				GoToPiggyEmptyingState();
			}
			else
			{
				RemoveAfterPurchaseInApps();

				await Children.RunToDispose(
					_paymentResultPopupControllerFactory,
					new PaymentsResultPopupsData(_overlayCanvas.transform, resultDescription),
					cancellationToken: token);

				GoToPreviousState();
			}

			Logger.ZLogInformation("Piggy: Purchasing product: {0}. Purchase result: {1}", _piggyPopupStateData.ProductData.Product.PaymentPageOptionId, resultDescription.Result);
		}

		private void RemoveAfterPurchaseInApps()
		{
			_inAppsCancellationTokenSource.Cancel();

			var conditionalTrigger = _conditionalTriggerProvider.GetConditionalTrigger(InAppsTriggerData.AfterPurchaseTrigger);

			_inAppsService.RemoveInApps(conditionalTrigger);
		}

		private void RemovePeggyExitInApps()
		{
			var conditionalTrigger = _conditionalTriggerProvider.GetConditionalTrigger(InAppsTriggerData.ExitPeggyAreaTrigger);

			_inAppsService.RemoveInApps(conditionalTrigger);
		}

		private void GoToPiggyEmptyingState()
		{
			CompletionSource.TrySetResult(GoTo(_piggyPopupRewardStateFactory.FromExtenject()).WithoutPayload());
		}

		private void RequestAvailableInApps()
		{
			_inAppsRefreshService.RefreshInApps(InAppsTriggerData.AfterPurchaseTrigger, _inAppsCancellationTokenSource.Token);
		}

		private void RemoveFinishedInApps()
		{
			RemovePiggyConditionalInApp(InAppsConditionalTriggerData.ConditionalPiggyIsFullLoginTrigger);
			RemovePiggyConditionalInApp(InAppsConditionalTriggerData.ConditionalPiggyIsFullBackToMapTrigger);

			void RemovePiggyConditionalInApp(InAppsConditionalTriggerData inAppTriggerData)
			{
				var inAppTrigger = _conditionalTriggerProvider.GetConditionalTrigger(inAppTriggerData);

				_activeInAppsService.RemoveInApps(inAppTrigger);
			}
		}

		private UniTask ConsumeShopProduct(PurchasingResultDescription resultDescription, CancellationToken token)
		{
			return _paymentsFacade.ConsumeShopProduct(resultDescription.ShopProduct, false, false, token);
		}

		private void ProcessWinStreakRewards()
		{
			var winStreakDuration = _piggyPopupStateData?.ProductData?.Product?.WinStreak ?? 0;

			if (winStreakDuration > 0)
			{
				_winStreakRewardNotifier.NotifyWinStreakReceived();
			}
		}
	}
}
Leave a Comment