using Assets.Scripts.Models;
//using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Unity.VectorGraphics;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class SendingFormController : MonoBehaviour
{
    static string uuid = "07a13c8907d1-6a7bdba1-a2fz-aatgu4j";
    public static string url; // = "http://dev.prmsys.net/api/areality/";
    //private static string proxy = "http://dev.prmsys.net/areditor/proxy.php?url=";
    // Start is called before the first frame update
    void Start()
    {
        //var r = PostRequest("http://test.prmsys.net/api/auth/usersinfo", "vsheiko", "8*9Efc2%");
        //Debug.Log(r.ToString());

    
    }

    // Update is called once per frame
    void Update()
    {

    }

    public static IEnumerator PostRequest(string controller, string api, Dictionary<string, string> data, Action<string, Dictionary<string, string>> callback = null, Action<WWW> errorCallback = null)
    {
        WWWForm form = new WWWForm();
        //form.AddField("login", login);
        //form.AddField("password", password);
        // form.headers.Add("uuid-key", "07a13c8907d1-6a7bdba1-a2fz-aatgu4j");
        Dictionary<string, string> headers = new Dictionary<string, string>()
        {
            { "uuid-key", uuid }
        };

        var url = controller + api;
        Debug.Log("api=" + url);
        WWW www;
        if (data != null)
        {
            foreach (var d in data)
                form.AddField(d.Key, d.Value);

            www = new WWW(url, form.data, headers);
        }
        else
        {
            www = new WWW(url, null, headers);
        }

        yield return www;

        if (string.IsNullOrEmpty(www.error))
        {
            //Debug.Log("Received: " + www.text);
            callback(www.text, data);
        }
        else
        {
            Debug.Log("Error While Sending: " + www.error);
            //if(data["param"] != null) errorCallback(www, data["param"]);
            //else 
                errorCallback(www);
        }
    }


    IEnumerator PostRequest(string url, string json)
    {
        var uwr = new UnityWebRequest(url, "POST");
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        uwr.SetRequestHeader("Content-Type", "application/json");

        //Send the request then wait here until it returns
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }


    // Web requests are typially done asynchronously, so Unity's web request system
    // returns a yield instruction while it waits for the response.
    //
    public static IEnumerator RequestRoutine(string url, Action<string> callback = null)
    {
        // Using the static constructor
        var request = UnityWebRequest.Get(url);

        // Wait for the response and then get our data
        yield return request.SendWebRequest();
        var data = request.downloadHandler.text;

        // This isn't required, but I prefer to pass in a callback so that I can
        // act on the response data outside of this function
        if (callback != null)
            callback(data);
    }

    // Callback to act on our response data
    private void ResponseCallback(string data)
    {
        Debug.Log(data);
    }

    /* public static IEnumerator LoadImage(Image img, System.Action<Texture2D> result)
     {
         WWW www = new WWW(url);
         yield return www;
         img.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
     }*/


    public static IEnumerator LoadImage(string url, GameObject plane, Vector3 pos = new Vector3(), Vector3 scale = new Vector3())
    {

        //string url = "https://example.com/image.jpeg";
        ////WWWForm form = new WWWForm();
        ////var headers = form.headers;
        ////headers["Access-Control-Allow-Credentials"] = "true";
        ////headers["Access-Control-Allow-Headers"] = "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time";
        ////headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
        //////headers["Access-Control-Allow-Origin"] = "http://test.prmsys.net/";
        ////headers["Content-type"] = "image/jpg, image/jpeg, image/png, image/bmp";

        using (UnityWebRequest img = UnityWebRequestTexture.GetTexture(url))
        {
            //Debug.Log(url);
            //var img = UnityWebRequestTexture.GetTexture(url); //, null, headers);

            yield return img.SendWebRequest();
            if (img.isNetworkError || img.isHttpError)
            {
                Debug.Log(img.error);
            }
            else
            {
                //Texture2D texture = new Texture2D(1, 1);
                var texture = DownloadHandlerTexture.GetContent(img);
                //img.LoadImageIntoTexture(texture);

                Renderer renderer = plane.GetComponent<Renderer>();
                renderer.material.mainTexture = texture;
                if (scale.x == 0 && scale.z == 0)
                {
                    plane.transform.localScale = new Vector3(texture.width / 1000f, 1, texture.height / 1000f);
                    scale = plane.transform.localScale;
                }
                else plane.transform.localScale = scale;
                if (pos.x == 0 && pos.z == 0)
                    plane.transform.position = new Vector3(scale.x * 5, 0, scale.z * 5);
                else plane.transform.position = pos;
                //GetComponent<Renderer>().material.mainTexture = img.texture;
            }
        }

    }

    /*public static IEnumerator LoadResources(string url_resources, string file, Action<Sprite> image = null, Action<WWW> errorCallback = null)
    {
        if (AuthorizationController.serverConfig != null)
        {
            //string url = "https://example.com/image.jpeg";
            WWWForm form = new WWWForm();
            //var headers = form.headers;
            //headers["Access-Control-Allow-Origin"] = "http://test.prmsys.net/areditor/";
            //headers["Access-Control-Allow-Credentials"] = "true";
            Debug.Log("proxy=" + AuthorizationController.serverConfig.proxy + url_resources + file);
            WWW img = new WWW(AuthorizationController.serverConfig.proxy + url_resources + file); //, null, headers);

            yield return img;

            if (String.IsNullOrEmpty(img.error))
            {
                var extension = System.IO.Path.GetExtension(file);
                //Debug.Log("extension: " + extension);

                //Debug.Log("Received: " + img.text);
                if (extension.Equals(".png")){
                    Texture2D texture = new Texture2D(1, 1);
                    img.LoadImageIntoTexture(texture);

                    image(StagesResourcesController.ConvertTextureToSprite(texture, file));
                }
                if (extension.Equals(".svg"))
                {
                    var tessOptions = new VectorUtils.TessellationOptions()
                    {
                        StepDistance = 100.0f,
                        MaxCordDeviation = 0.5f,
                        MaxTanAngleDeviation = 0.1f,
                        SamplingStepSize = 0.01f
                    };

                    // Dynamically import the SVG data, and tessellate the resulting vector scene.
                    var sceneInfo = SVGParser.ImportSVG(new StringReader(img.text));
                    var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

                    // Build a sprite with the tessellated geometry.
                    var sprite = VectorUtils.BuildSprite(geoms, 50.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
                    sprite.name = file;
                    image(sprite);
                }
                
            }
            else
            {
                Debug.Log("Error While Sending: " + img.error);
                errorCallback(img);
            }

            
            //GetComponent<Renderer>().material.mainTexture = img.texture;
        }
    }*/
}
