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

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

        public async Task<AdRequestInfo> GetAd(AdPlayTemplate template, CreativeShowType creativeShowType, BannerPlaceType bannerPlaceType)
        {
            if (template.Image == null)
            {
                Debug.LogError($"Adplay banner request failed: Image is null");
                return new AdRequestInfo(AdRequestResultState.MissingRequiredComponent, "Adplay banner request failed: Image is null");
            }

            var ad = GetCreative(creativeShowType, bannerPlaceType);
            int counter = 0;
            while (ad == null && counter < 10)
            {
                await Task.Delay(AdPlayUtility.DelayMilliTime);
                ad = GetCreative(creativeShowType, bannerPlaceType);
                counter++;
            }

            if (ad == null)
            {
                return new AdRequestInfo(AdRequestResultState.NoActiveAd);
            }

            Sprite sprite = activeAds.GetSprite(ad.Id);

            template.Hide();
            template.SetSprite(sprite);
            engagementData.CreateEngagement(ad.Id, EngagementType.IMP, ad);

            if (template.ClickButton && !string.IsNullOrEmpty(ad.ClickUrl))
            {
                template.ClickButton.onClick.AddListener(() =>
                {
                    engagementData.CreateEngagement(ad.Id, EngagementType.CLK, ad);
                    Application.OpenURL(ad.ClickUrl);
                });
            }

            template.Show();

            return new AdRequestInfo(AdRequestResultState.Success);
        }


        private Creative GetCreative(CreativeShowType creativeShowType, BannerPlaceType bannerPlaceType)
        {
            if (creativeShowType == CreativeShowType.Permanent)
            {
                return activeAds.GetPermanentCreatives(AdPlacementType.ProductPlacement, AdType.Banner, creativeShowType)
                    .FirstOrDefault(x => x.GetBannerPlaceType() == bannerPlaceType);
            }
            else if (creativeShowType == CreativeShowType.WeightBased)
            {
                var creatives = activeAds.GetWeightBaseCreatives(AdPlacementType.ProductPlacement, AdType.Banner);
                var banners = creatives.Where(c => c.GetBannerPlaceType() == bannerPlaceType).ToList();
                return activeAds.GetRandomCreative(banners);
            }
            else
                return null;

        }


    }
}
