using System;
using System.Collections.Generic;
using UnityEngine;
using ViKPI.Internal;

namespace ViKPI
{
    /// <summary>The player's answer to the data collection question.</summary>
    public enum VikpiConsentStatus
    {
        /// <summary>Not asked yet: nothing is collected.</summary>
        Unknown = 0,
        Granted = 1,
        /// <summary>Refused or withdrawn: nothing is collected.</summary>
        Denied = 2,
    }

    /// <summary>
    /// The ViKPI SDK. With the settings asset in place it starts on its own; most games only call
    /// <see cref="Track"/> and <see cref="SetUserId"/>. Every method is safe to call at any time,
    /// from the main thread, including before the SDK has started or after it was disabled.
    /// </summary>
    public static class Vikpi
    {
        public const string SdkVersion = "0.3.0";

        /// <summary>True once a session is running.</summary>
        public static bool IsRunning => VikpiRuntime.Instance != null && VikpiRuntime.Instance.HasSession;

        /// <summary>The current session id, or null. Handy for linking support tickets to replays.</summary>
        public static string SessionId => VikpiRuntime.Instance != null ? VikpiRuntime.Instance.SessionId : null;

        /// <summary>True while this session is being recorded as video.</summary>
        public static bool IsRecording => VikpiRuntime.Instance != null && VikpiRuntime.Instance.IsRecording;

        /// <summary>
        /// Starts the SDK when Auto Start is off (for example after the player gave consent).
        /// Arguments override the settings asset; pass none to use it as is.
        /// </summary>
        public static void Init(string apiKey = null, string endpoint = null)
        {
            VikpiRuntime.Boot(VikpiSettings.Load(), apiKey, endpoint, explicitInit: true);
        }

        /// <summary>
        /// Records a custom event. Names may use letters, digits, spaces and <c>_ . : -</c>, up to 64
        /// characters. Property values must be strings, numbers or booleans; up to 32 per event.
        /// </summary>
        public static void Track(string name, IDictionary<string, object> properties = null)
        {
            if (!EventValidator.IsValidName(name, allowSystem: false))
            {
                Log.WarnOnce("name:" + name, $"Event name \"{name}\" is invalid and was dropped. Use letters, digits, spaces and _ . : - (max 64), not starting with $.");
                return;
            }
            VikpiRuntime.Instance?.TrackEvent(name, properties);
        }

        /// <summary>Associates this and later sessions with your own player id. Pass null to clear it.</summary>
        public static void SetUserId(string userId)
        {
            if (userId != null && userId.Length > 128) userId = userId.Substring(0, 128);
            VikpiRuntime.SetUserId(userId);
        }

        /// <summary>Stops sending video for sensitive screens until <see cref="ResumeRecording"/>.</summary>
        public static void PauseRecording() => VikpiRuntime.Instance?.SetRecordingPaused(true);

        public static void ResumeRecording() => VikpiRuntime.Instance?.SetRecordingPaused(false);

        /// <summary>Sends buffered data now instead of at the next interval.</summary>
        public static void Flush() => VikpiRuntime.Instance?.FlushNow();

        /// <summary>Ends the session and stops the SDK until the next launch or <see cref="Init"/>.</summary>
        public static void Shutdown() => VikpiRuntime.ShutdownInstance();

        // ---------- privacy: consent and player rights ----------

        /// <summary>The player's stored choice. Nothing is collected unless it is Granted (or the consent mode is NotRequired).</summary>
        public static VikpiConsentStatus ConsentStatus => ConsentStore.Read();

        /// <summary>
        /// Records the player's choice. Use it with Consent Mode = Manual (your own dialog or a consent
        /// platform), or from a privacy toggle in your settings menu. <c>true</c> starts the SDK if it was
        /// waiting; <c>false</c> stops it at once and erases data not yet sent.
        /// </summary>
        public static void SetConsent(bool granted) => VikpiRuntime.SetConsent(granted);

        /// <summary>Shows the built-in consent prompt again, e.g. from a "Privacy" button in your settings.</summary>
        public static void ShowConsentPrompt()
        {
            var settings = VikpiSettings.Load() ?? VikpiSettings.CreateDefault();
            if (settings.AppTargetsChildren) return;
            ConsentPrompt.Show(settings, SetConsent);
        }

        /// <summary>Opens the privacy policy URL set under Project Settings → ViKPI.</summary>
        public static void OpenPrivacyPolicy()
        {
            var settings = VikpiSettings.Load();
            if (settings != null && settings.HasValidPrivacyPolicyUrl) Application.OpenURL(settings.PrivacyPolicyUrl.Trim());
            else Log.Warn("No privacy policy URL set under Project Settings → ViKPI.");
        }

        /// <summary>
        /// The player's right to erasure: stops collection, asks the server to delete every session,
        /// video and event recorded from this install, then forgets the install id. Offer it in your
        /// settings menu (Google Play and Apple expect players to be able to request deletion).
        /// The callback receives false if the server could not be reached; call again later.
        /// </summary>
        public static void RequestDataDeletion(Action<bool> onComplete = null) => VikpiRuntime.RequestDeletion(onComplete);
    }
}
