using Adplay.Model;
using Adplay.Utility;
using Adplay.View;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

namespace Adplay.Behaviours.Actions
{
    public class AdPlaySplash : AdPlayAction
    {
        private List<SplashInfo> splashDurationInfos = new();
        public async override Task<AdRequestInfo> GetAd(AdPlayTemplate template)
        {
            if (template.Image == null)
            {
                Debug.LogError($"Adplay splash request failed: Image is null");
                return new AdRequestInfo(AdRequestResultState.MissingRequiredComponent, "Adplay splash request failed: Image is null");
            }

            var ad = activeAds.GetActiveAd(AdType.Splash);
            int counter = 0;
            while (ad == null && counter < 10)
            {
                await Task.Delay(AdPlayUtility.DelayMilliTime);
                ad = activeAds.GetActiveAd(AdType.Splash);
                counter++;
            }
            if (ad == null)
            {
                return new AdRequestInfo(AdRequestResultState.NoActiveAd);
            }

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

            var splashInfo = CreateSplashInfo(ad.Id);
            template.OnShow += () =>
            {
                splashInfo.LastShowTime = Time.time;
            };

            template.OnDeactive += () =>
            {
                splashInfo.CalculateDuration();
                engagementData.UpdateDuration(ad.Id, splashInfo.Duration);
            };
            template.Show();

            return new AdRequestInfo(AdRequestResultState.Success);
        }

        private SplashInfo CreateSplashInfo(int adId)
        {
            var info = new SplashInfo()
            {
                AdId = adId,
            };
            splashDurationInfos.Add(info);
            return info;
        }


        [System.Serializable]
        private class SplashInfo
        {
            [field: SerializeField] public int AdId { get; set; }
            [field: SerializeField] public float LastShowTime { get; set; }
            [field: SerializeField] public float LastHideTime { get; set; }
            [field: SerializeField] public float Duration { get; private set; }

            public void CalculateDuration()
            {
                LastHideTime = Time.time;
                Duration += LastHideTime - LastShowTime;
            }
        }

    }
}
