﻿using AsmodeeDigital.Common.Plugin.Domain.CrossPromo;
using AsmodeeDigital.Common.Plugin.Utils;
using AsmodeeDigital.CrossPromo.Plugin.Utils;
using AsmodeeDigital.CrossPromo.Plugin.View;
using System;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Plugins.AsmodeeDigital.CrossPromo.Code.UI
{
    public class Banner : MonoBehaviour
    {
        [Serializable]
        public class UI
        {
            public RectTransform RectTransform;
            public RawImage Image;
        }

        public UI ui;
        public BannerPosition Position = BannerPosition.Top;

        private ScreenOrientation _previousOrientation = ScreenOrientation.Unknown;
        private Product _product;

        private void Start()
        {
            RefreshBanner();
            DeviceScaler.Instance.DeviceOrientationChangedEvent += RefreshBanner;
        }

        public void Init(Product product)
        {
            _product = product;

            ui.Image.gameObject.SetActive(false);

            StartCoroutine(TextureLoader.LoadTexture(product.banner_url, ui.Image));
        }

        public void RefreshBanner()
        {
            float scale = CrossPromoView.Instance.ui.CanvasScaler.referenceResolution.y / (float)Screen.height;

            float height = Mathf.Max(Screen.width, Screen.height) / 8f;
            float width = 5f * height;

            this.ui.Image.rectTransform.sizeDelta = new Vector2(width, height) * scale;

            if (Position == BannerPosition.Top)
            {
                this.ui.RectTransform.anchorMin = new Vector2(0.5f, 1f);
                this.ui.RectTransform.anchorMax = new Vector2(0.5f, 1f);
                this.ui.RectTransform.pivot = new Vector2(0.5f, 1f);
            }
            else
            {
                this.ui.RectTransform.anchorMin = new Vector2(0.5f, 0f);
                this.ui.RectTransform.anchorMax = new Vector2(0.5f, 0f);
                this.ui.RectTransform.pivot = new Vector2(0.5f, 0f);
            }

            this.ui.Image.rectTransform.anchorMin = this.ui.RectTransform.anchorMin;
            this.ui.Image.rectTransform.anchorMax = this.ui.RectTransform.anchorMax;
            this.ui.Image.rectTransform.pivot = this.ui.RectTransform.pivot;
        }

        public void Hide()
        {
            this.ui.Image.gameObject.SetActive(false);
        }

        public bool IsVisible()
        {
            return ui.Image.gameObject.activeInHierarchy;
        }

        public void Banner_Clicked()
        {
            CrossPromoView.Instance.ShowGameDetailsPopup(_product);
        }
    }

    public enum BannerPosition
    {
        Top,
        Bottom
    }
}
