using System.Threading.Tasks;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;

#if STEAMWORKS_NET
using HeathenEngineering.SteamworksIntegration;
using Friends = HeathenEngineering.SteamworksIntegration.API.Friends;
using API = HeathenEngineering.SteamworksIntegration.API;
using System;
using Steamworks;
#endif

#if UNITY_EDITOR
using ParrelSync;
#endif

public static class Authentication {
    public static string PlayerId { get; private set; }
    static string identity = "unityauthenticationservice";

    public static bool IsLoggedIn()
    {
        return UnityServices.State == ServicesInitializationState.Initialized && AuthenticationService.Instance.IsSignedIn;
    }

    public static async Task Login() {
        if (UnityServices.State == ServicesInitializationState.Uninitialized) {
            var options = new InitializationOptions();


#if UNITY_EDITOR
            // Remove this if you don't have ParrelSync installed. 
            // It's used to differentiate the clients, otherwise lobby will count them as the same
            if (ClonesManager.IsClone()) options.SetProfile(ClonesManager.GetArgument());
            else options.SetProfile("Primary");
#endif
            
            await UnityServices.InitializeAsync(options);
        }

        if (!AuthenticationService.Instance.IsSignedIn) {

#if STEAMWORKS_NET
            bool initialized = Steamworks.SteamAPI.Init();
            if (initialized) {
                var task = new TaskCompletionSource<string>();
                API.Authentication.GetWebAuthSessionTicket(identity, (AuthenticationTicket ticket, bool failure) => {
                    Debug.Log($"GetAuthSessionTicket success with ticket: {ticket} and failure: {failure}");
                    string sessionTicket = BitConverter.ToString(ticket.Data).Replace("-", string.Empty);
                    task.SetResult(sessionTicket);
                });
                string sessionTicket = await task.Task;
                Debug.Log($"SignInWithSteamAsync with appId: {AppData.Me.AppId}");
                await AuthenticationService.Instance.SignInWithSteamAsync(sessionTicket, identity, AppData.Me.AppId.ToString());
            } else {
                Debug.Log("Unable to init steam api");
                await AuthenticationService.Instance.SignInAnonymouslyAsync();
            }
#else
            await AuthenticationService.Instance.SignInAnonymouslyAsync();
#endif

            PlayerId = AuthenticationService.Instance.PlayerId;
        }
    }
}