using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using SFB;
using UnityEngine.Networking;
using System.IO;
using System;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

public class FileBrowserController : MonoBehaviour, IPointerDownHandler
{
    public InputField inputField;
    // Warning: paths returned by FileBrowser dialogs do not contain a trailing '\' character
    // Warning: FileBrowser can only show 1 dialog at a time

#if UNITY_WEBGL && !UNITY_EDITOR
    //
    // WebGL
    //
    [DllImport("__Internal")]
    private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);

    public void OnPointerDown(PointerEventData eventData) {
        UploadFile(gameObject.name, "OnFileUpload", ".png, .jpg", false);
        Debug.Log("OnPointerDown");
    }

    // Called from browser
    public void OnFileUpload(string url) {
        StartCoroutine(UpLoadUserData(url));
    }
#else
    //
    // Standalone platforms & editor
    //
    public void OnPointerDown(PointerEventData eventData) { }

    void Start()
    {
        var button =GetComponent<Button>();
        button.onClick.AddListener(OnClick);
    }

    //public void OpenFileBrowser()
    //{
    //    ShowLoadDialogCoroutine($"Выбор объекта", new ExtensionFilter("Vuforia Files", "xml", "dat"));
    //}
#endif

    public void OnClick()
    {
        // Open file
        string[] paths = new string[0];

        paths = StandaloneFileBrowser.OpenFilePanel($"Выбор изображения", "", "png,jpg", false);
     
        if (paths.Length > 0)
        {
            Debug.Log(paths[0]);
            StartCoroutine(UpLoadUserData(paths[0]));
        }
    }

    /// <summary>
    /// Отправка файла на сервер
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator UpLoadUserData(string url)
    {
       // Debug.Log(url);
        WWWForm form = new WWWForm();
        UnityWebRequest www;
        string file_name;
        string php = "";
        if (Application.platform == RuntimePlatform.WebGLPlayer)
        {
            var deserialize = JsonConvert.DeserializeObject<List<urls>>(url);
            file_name = deserialize[0].file_name;
            Debug.Log($"file image {file_name}");
            var base64 = Regex.Match(deserialize[0].base64, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;//match.Groups["type"].Value;
            //string base64 = deserialize[0].base64.Substring(deserialize[0].base64.IndexOf(',') + 1);
            //base64 = base64.Trim('\0');
            byte[] bytes = Convert.FromBase64String(base64);// Encoding.UTF8.GetBytes(deserialize[0].base64);
            Debug.Log($"bytes {bytes.Length}");
            form.AddBinaryData("file", bytes, deserialize[0].file_name);
            php = $"{Application.streamingAssetsPath}/upload.php";
        }
        else
        {
            file_name = Path.GetFileName(url);
            using (FileStream fstream = File.OpenRead(url))
            {
                // преобразуем строку в байты
                byte[] bytes = new byte[fstream.Length];
                fstream.Read(bytes, 0, bytes.Length);
                form.AddBinaryData("file", bytes, file_name);//{Path.GetExtension(url)}
                php = $"http://dev.prmsys.net/positionviewer/StreamingAssets/upload.php";
            }           
        }
        www = UnityWebRequest.Post(php, form);
        yield return www.SendWebRequest();
        if (www.isHttpError)
            Debug.Log(www.error);
        else
        {
            Debug.Log("Uploaded");
            inputField.text = $"{Application.streamingAssetsPath}/{file_name}";
            EditorController.instance.UpdatePanel();
            Debug.Log(www.downloadHandler.text);
        }
      
    }

    class urls
    {
        public string file_name { get; set; }
        public string base64 { get; set; }
    }
}



