using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System;
using UnityEngine.Purchasing;
using UnityEngine.UI; //could this be it????
using UnityEngine.Purchasing.Extension; // Added this line

//Stores data of Consumable products
//Consumable items can be purchased again and again such as coins.


//IDetailedStoreListener provides callbacks for handling purchases
public class StoreScript : MonoBehaviour, IDetailedStoreListener{


    IStoreController m_StoreController; // The Unity Purchasing system.

    //Your products IDs. They should match the ids of your products in your store.
    public string catProductId = "com.ex.cat";
    public string eagleProductId = "com.ex.eagle";
    public string cheetahProductId = "com.ex.cheetah";
    public string hyenaProductId = "com.ex.hyena";

    public string subscriptionProductId = "com_ex_battlepass";
    // public string diamondProductId = "com.mycompany.mygame.diamond1";

    // public Text GoldCountText;
    // public Text DiamondCountText;

    // int m_GoldCount;
    // int m_DiamondCount;

    // public TextMeshProUGUI debug_msg;

    MissionHandler mission_handler;
    public GameObject missionhandler_holder;
    void OnEnable(){
        mission_handler = missionhandler_holder.GetComponent<MissionHandler>();
    }

    void Start()
    {
        // ErrorField = GameObject.Find("ErrorField").GetComponent<TMP_Text>();
        InitializePurchasing();
        // UpdateUI();
        // PopulateCanvasWithPrefabs();
    }
    
    //Set up a configuration builder, add consumable products to it and initialize Unity Purchasing
    void InitializePurchasing()
    {
        try{
            var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

            //Add products that will be purchasable and indicate its type.
            builder.AddProduct(catProductId, ProductType.NonConsumable);
            builder.AddProduct(eagleProductId, ProductType.NonConsumable);
            builder.AddProduct(cheetahProductId, ProductType.NonConsumable);
            builder.AddProduct(hyenaProductId, ProductType.NonConsumable);

            builder.AddProduct(subscriptionProductId, ProductType.Subscription);
            // builder.AddProduct(diamondProductId, ProductType.Consumable);

            UnityPurchasing.Initialize(this, builder);    
        }catch(Exception e){
            // ErrorField.text = e.ToString();
        }
        
    }

    public void BuyGold(string item_id)
    {
        //Seems to be the problem
        // m_StoreController.InitiatePurchase(goldProductId);
        // Debug.Log("Hk");

        try{
            m_StoreController.InitiatePurchase(item_id);
        }catch(Exception e){
            // debug_msg.text = "Err: " + e.ToString();
        }
        
    }

    public void BuySubscription(){
        // debug_msg.text = subscriptionProductId;
        try{
            m_StoreController.InitiatePurchase(subscriptionProductId);
        }catch(Exception e){
            // debug_msg.text = "InitiatePurchase_Error: " + e.ToString();
            // msg.text = "InitiatePurchase_Error: " + e.ToString();
        }
    }

    // public void BuyDiamond()
    // {
    //     m_StoreController.InitiatePurchase(diamondProductId);
    // }

    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        // ErrorField.text = "In-App Purchasing successfully initialized";

        Debug.Log("In-App Purchasing successfully initialized");
        m_StoreController = controller;
    }

    public void OnInitializeFailed(InitializationFailureReason error)
    {
        OnInitializeFailed(error, null);
    }

    public void OnInitializeFailed(InitializationFailureReason error, string message)
    {
        var errorMessage = $"Purchasing failed to initialize. Reason: {error}.";

        if (message != null)
        {
            errorMessage += $" More details: {message}";
        }

        // ErrorField.text = errorMessage;
        Debug.Log(errorMessage);
    }

    //Processing purchase
    //Check if user successfully purchased or declined, also return the item purchased
    //This function is called when a purchase is completed  ????????
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        //Retrieve the purchased product
        var product = args.purchasedProduct;

        // switch(product.definition.id){
        // }

        if (product.definition.id == catProductId){
            mission_handler.CharacterUnlocked("Cat(Clone)");
        }

        if (product.definition.id == eagleProductId){
            mission_handler.CharacterUnlocked("Eagle(Clone)");
        }

        if (product.definition.id == cheetahProductId){
            mission_handler.CharacterUnlocked("Cheetah(Clone)");
        }

        if (product.definition.id == hyenaProductId){
            mission_handler.CharacterUnlocked("Hyena(Clone)");
        }




        //Add the purchased product to the players inventory
        // if (product.definition.id == goldProductId)
        // {
        //     // ErrorField.text = $"Adding Gold... {product.definition.id}";
        //     // AddGold();
        // }
        // else if (product.definition.id == diamondProductId)
        // {
        //     AddDiamond();
        // }

        // ErrorField.text = $"Purchase Complete - Product: {product.definition.id}";
        Debug.LogWarning($"Purchase Complete - Product: {product.definition.id}");

        //We return Complete, informing IAP that the processing on our side is done and the transaction can be closed.
        return PurchaseProcessingResult.Complete;
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        // ErrorField.text = $"Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}";
        Debug.Log($"Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}");
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
    {
        // ErrorField.text = $"Purchase failed - Product: '{product.definition.id}'," +
        //     $" Purchase failure reason: {failureDescription.reason}," +
        //     $" Purchase failure details: {failureDescription.message}";

        Debug.Log($"Purchase failed - Product: '{product.definition.id}'," +
            $" Purchase failure reason: {failureDescription.reason}," +
            $" Purchase failure details: {failureDescription.message}");
    }

    void AddGold()
    {
        // m_GoldCount++;
        UpdateUI();
    }

    // void AddDiamond()
    // {
    //     m_DiamondCount++;
    //     UpdateUI();
    // }

    void UpdateUI()
    {
        // ErrorField.text = "50 Gold Added";
        // GoldCountText.text = $"Your Gold: {m_GoldCount}";
        // DiamondCountText.text = $"Your Diamonds: {m_DiamondCount}";
    }
}
