using System;
using Innoactive.AccessControl.Authorizer;
using Innoactive.AccessControl.OAuth2;
using UnityEngine;

namespace Innoactive.AccessControl
{
    /// <summary>
    /// Authorizes the user's access to this application
    /// </summary>
    public class AuthorizationManager : MonoBehaviour
    {
        /// <summary>
        /// Called when the user was successfully authorized to use the application.
        /// </summary>
        public event EventHandler OnAuthorizationSuccessful;

        /// <summary>
        /// Called when the user could not be authorized.
        /// </summary>
        public event EventHandler OnAuthorizationFailed;

        [SerializeField]
        private OAuth2ClientSettings oAuth2ClientSettings;

        private IAuthorizer authorizer;

        private void Reset()
        {
            if (oAuth2ClientSettings == null)
            {
                oAuth2ClientSettings = Resources.Load<OAuth2ClientSettings>("OAuth2ClientSettings");
            }
        }

        private void Awake()
        {
#if UNITY_EDITOR
            authorizer = new EditorAuthorizer();
#elif UNITY_ANDROID
            authorizer = new AndroidAuthorizer();
#elif UNITY_STANDALONE_WIN
            authorizer = new WindowsAuthorizer();
#else
            authorizer = new UnsupportedPlatformAuthorizer();
#endif
        }

        private void Start()
        {

#if UNITY_STANDALONE_WIN || UNITY_EDITOR
            if (oAuth2ClientSettings == null)
            {
                Debug.LogError("No configuration for OAuth2 client provided. Cannot proceed with Authorization");
                EmitFailEvent();
                return;
            }
#endif

            if (authorizer.Authorize(oAuth2ClientSettings))
            {
                EmitSuccessEvent();
            }
            else
            {
                EmitFailEvent();
            }
        }

        private void EmitSuccessEvent()
        {
            Debug.Log("EmitSuccessEvent");
            OnAuthorizationSuccessful?.Invoke(this, new EventArgs());
        }

        private void EmitFailEvent()
        {
            Debug.Log("EmitFailEvent");
            OnAuthorizationFailed?.Invoke(this, new EventArgs());
        }
    }
}
