using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.ComponentModel;
using UnityEngine.Networking;

namespace GameNetwork {
    
    public class ImageRequest : MonoBehaviour
    {
        
        public delegate void ImageRequestResponse (bool success, Sprite sprite);

        EventHandlerList listEventDelegates = new EventHandlerList ();
        static ImageRequest _instance = null;

        static public ImageRequest Instance {
            get {
                if (_instance == null) {
                    _instance = FindObjectOfType<ImageRequest> ();
                    if (_instance == null) {
                        // create gameobject and add component 
                        GameObject obj = new GameObject ();
                        obj.name = "ImageRequest";
                        _instance = obj.AddComponent<ImageRequest> ();
                        DontDestroyOnLoad (obj);
                    }
                }
                return _instance;
            }
        }

        public void Request(string URLString, ImageRequestResponse handler) {
            string key = System.DateTime.Now.ToString ("yyyyMMddHHmmssffff");

            listEventDelegates.AddHandler (key, handler);

            #if UNITY_2017_1_OR_NEWER
            StartCoroutine (imageFromUrl(URLString, key));
            #else
            StartCoroutine (imageFromUrlOldVersion(URLString, key));
            #endif
        }

        IEnumerator imageFromUrl(string URLString, string key) {
            UnityWebRequest request = UnityWebRequestTexture.GetTexture(URLString);
            yield return request.SendWebRequest();

            if (request.isNetworkError || request.isHttpError) {
                Debug.Log("request.error = " + request.error);
            } else if (!request.isDone) {
                yield return request;
            }
            else {
                Texture2D texture2D = ((DownloadHandlerTexture) request.downloadHandler).texture;
                Rect rect = new Rect(0, 0, texture2D.width, texture2D.height);
                Sprite sprite = Sprite.Create(texture2D, rect, new Vector2(0.5f, 0.5f));

                requestHandler(key, sprite);
            }
        }

        IEnumerator imageFromUrlOldVersion(string URLString, string key) {
            WWW www = new WWW(URLString);

            // Wait for download to complete
            yield return www;

            // assign texture
            Renderer renderer = GetComponent<Renderer>();
            Texture2D texture2D = www.texture;
            Rect rect = new Rect(0, 0, texture2D.width, texture2D.height);
            Sprite sprite = Sprite.Create(texture2D, rect, new Vector2(0.5f, 0.5f));

            requestHandler(key, sprite);
        }

        private void requestHandler(string key, Sprite sprite) {
            ImageRequestResponse handler = (ImageRequestResponse)listEventDelegates [(object)key];

            listEventDelegates.RemoveHandler(key, handler);

            if (handler != null) {
                handler (true, sprite); // TODO : Success 값..
            }
            // DestroyObject();
        }
    }

}