Playvoi/Assets/ShiroginSDK/Runtime/Services/Implementations/Facebook/FacebookService.cs
2025-10-30 22:48:16 +03:00

122 lines
No EOL
3.8 KiB
C#

using System;
using System.Collections.Generic;
using Facebook.Unity;
using ShiroginSDK.Runtime.Services.Base;
using ShiroginSDK.Runtime.Services.Interfaces;
using UnityEngine;
namespace ShiroginSDK.Runtime.Services.Implementations.Facebook
{
/// <summary>
/// Handles Facebook SDK initialization, login, and event tracking.
/// Now managed as a ServiceBase implementation for modular SDK integration.
/// </summary>
public class FacebookService : ServiceBase, IFacebookService
{
private bool _isInitialized;
// ----------------------------------------------------
// Initialization
// ----------------------------------------------------
public void Initialize()
{
if (_isInitialized)
return;
if (!FB.IsInitialized)
{
FB.Init(OnInitComplete, OnHideUnity);
}
else
{
FB.ActivateApp();
_isInitialized = true;
}
}
// ----------------------------------------------------
// Login
// ----------------------------------------------------
public void Login(Action<bool, string> callback = null)
{
if (!_isInitialized)
{
Debug.LogWarning("[FacebookService] ⚠️ Login attempted before initialization.");
callback?.Invoke(false, null);
return;
}
var permissions = new List<string> { "public_profile", "email" };
FB.LogInWithReadPermissions(permissions, result =>
{
if (FB.IsLoggedIn)
{
var userId = AccessToken.CurrentAccessToken.UserId;
Debug.Log($"[FacebookService] ✅ Login successful: {userId}");
callback?.Invoke(true, userId);
}
else
{
Debug.LogWarning("[FacebookService] ❌ Login failed.");
callback?.Invoke(false, null);
}
});
}
// ----------------------------------------------------
// Analytics
// ----------------------------------------------------
public void LogPurchase(float amount, string currency)
{
if (!_isInitialized)
{
Debug.LogWarning("[FacebookService] ⚠️ LogPurchase called before SDK init.");
return;
}
FB.LogPurchase(amount, currency);
Debug.Log($"[FacebookService] 💰 Purchase logged: {amount} {currency}");
}
public void LogEvent(string eventName, float? value = null, Dictionary<string, object> parameters = null)
{
if (!_isInitialized)
{
Debug.LogWarning("[FacebookService] ⚠️ LogEvent called before SDK init.");
return;
}
if (value.HasValue)
FB.LogAppEvent(eventName, value.Value, parameters);
else
FB.LogAppEvent(eventName, null, parameters);
Debug.Log($"[FacebookService] 📊 Event logged: {eventName}");
}
// ----------------------------------------------------
// Lifecycle
// ----------------------------------------------------
protected override void OnInitialize()
{
Initialize();
}
protected override void OnDispose()
{
// Nothing to dispose for now
}
private void OnInitComplete()
{
_isInitialized = true;
FB.ActivateApp();
Debug.Log("[FacebookService] ✅ SDK Initialized.");
}
private void OnHideUnity(bool isGameShown)
{
Time.timeScale = isGameShown ? 1 : 0;
}
}
}