using Adplay.DataContainer;
using Adplay.Model;
using Adplay.Utility;
using System.Threading.Tasks;
using UnityEngine;

namespace Adplay.Behaviours.Actions
{
    public class AdPlayInterstitialSound : MonoBehaviour
    {

        [SerializeField] private AudioSource audioSource;
        [SerializeField] private SoundAds soundAds;
        [SerializeField] private EngagementData engagementData;

        public async Task<AdRequestInfo> GetAd()
        {
            AudioListener listener = FindFirstObjectByType<AudioListener>();

            if (listener == null)
                return new AdRequestInfo(AdRequestResultState.MissingRequiredComponent, "Adplay Interstitial Sound request failed: No active AudioListener in scene");

            if (audioSource == null)
                return new AdRequestInfo(AdRequestResultState.MissingRequiredComponent, "Adplay Interstitial Sound request failed: Audio source is null");

            var soundAd = soundAds.GetSound();
            int counter = 0;
            while (soundAd == null && counter < 10)
            {
                await Task.Delay(AdPlayUtility.DelayMilliTime);
                soundAd = soundAds.GetSound(AdType.InterstitialSound);
                counter++;
            }

            if (soundAd == null)
            {
                return new AdRequestInfo(AdRequestResultState.NoActiveAd, "Adplay Interstitial Sound request failed: No active ad sound");
            }

            audioSource.PlayOneShot(soundAd.AudioClip);
            engagementData.CreateEngagement(IdGenerator.NewId(), EngagementType.VOI, soundAd.Creative);
            return new AdRequestInfo(AdRequestResultState.Success);
        }

    }

}