using System;
using UnityEngine;
using TMPro;
using System.Runtime.InteropServices;
using AOT;
using FRVR;

public class frvrtest : MonoBehaviour
{
    public Texture2D shareTexture;
    public TMP_Text textOutput;

    // Static variables to hold data for callbacks
    private static string s_originalJSON = "{\"score\":1,\"level\":3,\"state\":\"\"}";
    private static frvrtest s_instance;

    // Custom logging method that forwards to textOutput
    private void LogToOutput(string message)
    {
        Debug.Log(message);
        if (textOutput != null)
        {
            textOutput.text += message + "\n";
        }
    }

    void TestLogging()
    {
        FRVRSDK.Analytics.LogFTUE(1, "test");
        FRVRSDK.Analytics.LogLevelStart("Level 1 start");
        FRVRSDK.Analytics.LogLevelEnd("Level 1 end");
        FRVRSDK.Analytics.LogEvent("test event", "{\"test\": \"test\"}");
    }

    // Static callback methods for IL2CPP compatibility
    [MonoPInvokeCallback(typeof(Action<int>))]
    private static void OnSetLocalJsonComplete(int result)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("SetLocalJson result: " + result);

            if (result == 0)
            {
                Debug.LogError("SetLocalJson failed");
                return;
            }

            FRVRSDK.Data.GetLocalJson(OnGetLocalJsonComplete);
        }
    }

    [MonoPInvokeCallback(typeof(Action<string>))]
    private static void OnGetLocalJsonComplete(string json)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("GetLocalJson result: " + json);

            if (json != s_originalJSON)
            {
                Debug.LogError("GetLocalJson failed");
                return;
            }

            s_instance.LogToOutput("GetLocalJson succeeded");
        }
    }

    [MonoPInvokeCallback(typeof(Action<string>))]
    private static void OnIapPurchaseComplete(string result)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("IAP purchase result: " + result);
        }
    }

    [MonoPInvokeCallback(typeof(Action<string>))]
    private static void OnIapConsumePurchaseComplete(string purchaseId)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("IAP consume purchase result: " + purchaseId);
        }
    }

    [MonoPInvokeCallback(typeof(Action<string>))]
    private static void OnIapGetUnconsumedPurchasesComplete(string purchasesJson)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("IAP unconsumed purchases: " + purchasesJson);
        }
    }

    [MonoPInvokeCallback(typeof(Action<int>))]
    private static void OnShareComplete(int result)
    {
        if (s_instance != null)
        {
            s_instance.LogToOutput("Share result: " + result);
        }
    }

    void TestLocalVars()
    {
        // First test loading process
        FRVRSDK.Data.GetLocalJson(OnGetLocalJsonComplete);

        FRVRSDK.Data.SetLocalJson(s_originalJSON, OnSetLocalJsonComplete);

    }


    void TestAds()
    {

    }


    void TestIAP()
    {
        if (FRVRSDK.IAP.IsReady())
        {
            LogToOutput("IAP is ready");

            string catalog = FRVRSDK.IAP.GetCatalog();
            LogToOutput("IAP catalog: " + catalog);

            string productId = "com.frvr.test.product";
            FRVRSDK.IAP.GetProduct(productId);
            FRVRSDK.IAP.Purchase(productId, OnIapPurchaseComplete);

            // Test consume purchase
            string purchaseJson = "{\"productId\":\"testProductId\",\"purchaseId\":\"testPurchaseId\"}";
            FRVRSDK.IAP.ConsumePurchase(purchaseJson, OnIapConsumePurchaseComplete);

            // Test get unconsumed purchases
            FRVRSDK.IAP.GetUnconsumedPurchases(OnIapGetUnconsumedPurchasesComplete);
        }
        else
        {
            Debug.LogError("IAP is not ready");
        }
    }

    void TestShare()
    {
        string imageBase64 = "data:image/png;base64," + System.Convert.ToBase64String(shareTexture.EncodeToPNG());

        FRVRSDK.Social.Share("Check out Fruit Sort FRVR. Who needs sleep anyway?",
            imageBase64,
            "Share Fruit Sort FRVR",
            "Share",
            OnShareComplete);
    }

    // Example: Remove a single cloud storage item
    void TestRemoveCloudItem()
    {
        string itemKey = "itemKey";
        FRVRSDK.Data.RemoveCloudItem(itemKey, (result) =>
        {
            if (result == 1)
            {
                LogToOutput("Successfully removed cloud item: " + itemKey);
            }
            else
            {
                LogToOutput("Failed to remove cloud item: " + itemKey);
            }
        });
    }

    // Example: Remove multiple cloud storage items
    void TestRemoveCloudItems()
    {
        string[] keys = new string[] { "someKey1", "someKey2", "someKey3" };
        FRVRSDK.Data.RemoveCloudItems(keys, (result) =>
        {
            if (result == 1)
            {
                LogToOutput("Successfully removed " + keys.Length + " cloud items");
            }
            else
            {
                LogToOutput("Failed to remove cloud items");
            }
        });
    }

    // Example: Remove a single localStorage item
    void TestRemoveLocalItem()
    {
        string itemKey = "itemKey";
        FRVRSDK.Data.RemoveItem(itemKey, (result) =>
        {
            if (result == 1)
            {
                LogToOutput("Successfully removed local item: " + itemKey);
            }
            else
            {
                LogToOutput("Failed to remove local item: " + itemKey);
            }
        });
    }

    // Example: Remove multiple localStorage items
    void TestRemoveLocalItems()
    {
        string[] keys = new string[] { "someKey1", "someKey2", "someKey3" };
        FRVRSDK.Data.RemoveItems(keys, (result) =>
        {
            if (result == 1)
            {
                LogToOutput("Successfully removed " + keys.Length + " local items");
            }
            else
            {
                LogToOutput("Failed to remove local items");
            }
        });
    }

    void Start()
    {
        // Set the static instance reference
        s_instance = this;

        // TestLogging();
        // TestLocalVars();
        // TestAds();
        // TestIAP();
        // TestShare();

        // Not implemented yet, so no tests
        //  GetFeature(string featureId, StringResult d); 
    }

    public void TestSave()
    {
        s_originalJSON = "{\"score\":1,\"level\":3,\"state\":\"\"}";

        FRVRSDK.Data.SetLocalJson(s_originalJSON, OnSetLocalJsonComplete);
    }

    public void TestLoad()
    {
        FRVRSDK.Data.GetLocalJson(OnGetLocalJsonComplete);
    }

}

/*
// Calls from WebGL wrapper to Unity
// Mute the game
unityInstance.SendMessage('FRVRSDKSingleton', 'MuteVolumeInstance', '');

// Unmute the game
unityInstance.SendMessage('FRVRSDKSingleton', 'UnmuteVolumeInstance', '');

// Set volume to 50%
unityInstance.SendMessage('FRVRSDKSingleton', 'SetVolumeInstance', '0.5');

// Or using the float version (if your WebGL build supports it)
unityInstance.SendMessage('FRVRSDKSingleton', 'SetVolumeInstance', 0.5);
*/