﻿using System;
using System.Collections;
using System.IO;
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, MaskableGraphic image, Action<byte[]> afterLoading = null)
        {
            Texture2D texture = null;
            byte[] downloadedBytes = null;

            //---> Web image
            if (url.StartsWith("http"))
            {
                WWW www = new WWW(url);
                while (!www.isDone)
                {
                    yield return null;
                }

                texture = www.texture;
                downloadedBytes = www.bytes;
            }
            //---> Static cache (Resources)
            else if (url.Contains("Resources"))
            {
                string path = GetResourcePath(url);

                texture = Resources.Load<Texture2D>(path);
                texture.anisoLevel = 16;
            }
            //---> Local cache (application data)
            else
            {
                downloadedBytes = File.ReadAllBytes(url);
                texture = new Texture2D(2, 2, TextureFormat.RGBA32, false, false);
                texture.LoadImage(downloadedBytes);
                texture.anisoLevel = 16;
            }

            if (image != null && image.gameObject != null && texture != null)
            {
                if (image is Image)
                    ((Image)image).sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
                else if (image is RawImage)
                    ((RawImage)image).texture = texture;
                else
                    Debug.LogError("parameter image is not of type Image or RawImage");

                yield return null;

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

                yield return null;

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

        private static string GetResourcePath(string path)
        {
            path = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path));
            int indexResources = path.IndexOf("Resources");
            path = path.Substring(indexResources + "Resources/".Length).Replace("\\", "/");

            return path;
        }
    }
}
