﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace AsmodeeDigital.Common.Plugin.Utils
{
    /// <summary>
    /// Load asynchronously a web texture into an Image (UI) component
    /// </summary>
    public class TextureLoader
    {
        /// <summary>
        /// Load asynchronously a web texture into an Image (UI) component
        /// </summary>
        /// <param name="url">URI of the web image resource</param>
        /// <param name="image">UI component, destination of the texture</param>
        /// <returns></returns>
        public static IEnumerator LoadTexture(string url, Image image, Action afterLoading = null)
        {
            WWW www = new WWW(url);
            while (!www.isDone)
            {
                yield return null;
            }

            if (image != null && image.gameObject != null)
            {
                image.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), Vector2.zero);

                yield return null;

                image.enabled = true;
                image.gameObject.SetActive(true);

                yield return null;

                if (afterLoading != null)
                    afterLoading();
            }
        }

        /// <summary>
        /// Load asynchronously a web texture into an Image (UI) component
        /// </summary>
        /// <param name="url">URI of the web image resource</param>
        /// <param name="image">UI component, destination of the texture</param>
        /// <returns></returns>
        public static IEnumerator LoadTexture(string url, RawImage image, Action afterLoading = null)
        {
            WWW www = new WWW(url);
            while (!www.isDone)
            {
                yield return null;
            }

            if (image != null && image.gameObject != null && string.IsNullOrEmpty(www.error))
            {
                image.texture = www.texture;

                yield return null;

                image.enabled = true;
                image.gameObject.SetActive(true);

                yield return null;

                if (afterLoading != null)
                    afterLoading();
            }
        }
    }
}
