using Adplay.Model;
using Adplay.Utility;
using Adplay.View;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;

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

        [SerializeField] private AudioSource audioSource;

        public async Task<AdRequestInfo> GetAd(CreativeShowType creativeShowType)
        {
            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 = GetCreative(creativeShowType);
            int counter = 0;
            while (soundAd == null && counter < 10)
            {
                await Task.Delay(AdPlayUtility.DelayMilliTime);
                soundAd = GetCreative(creativeShowType);
                counter++;
            }

            if (soundAd == null)
            {
                return new AdRequestInfo(AdRequestResultState.NoActiveAd, "Adplay Interstitial Sound request failed: No active ad sound");
            }
            var soundAdInfo = AdPlayCacheService.GetSound(soundAd.Id);
            audioSource.PlayOneShot(soundAdInfo.AudioClip);
            engagementData.CreateEngagement(IdGenerator.NewId(), EngagementType.VOI, soundAdInfo.Creative);
            return new AdRequestInfo(AdRequestResultState.Success);
        }


        protected Creative GetCreative(CreativeShowType creativeShowType)
        {
            if (creativeShowType == CreativeShowType.Permanent)
            {
                return activeAds.GetPermanentCreatives(AdPlacementType.VoicePlacement, AdType.InterstitialSound, creativeShowType)
                    .FirstOrDefault();
            }
            else if (creativeShowType == CreativeShowType.WeightBased)
            {
                return activeAds.GetWeightBaseCreative(AdPlacementType.VoicePlacement, AdType.InterstitialSound, creativeShowType);
            }
            else
                return null;

        }

    }

}