using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;
using UnityEngine.UI;
using UnityEngine.Video;
using RTLTMPro;
using Paroxe.PdfRenderer;

[Serializable]
public class FileData
{
    public string id;
    public string link;
    public string type;
    public string status;
}

[Serializable]
public class ApiResponse
{
    public int status;
    public List<FileData> data;
    public string message;
}

public class ApiConnection : MonoBehaviour
{
    private string apiUrl = "http://185.116.161.39:8012/hivad/vr/files.php";
    public List<string> imageLinks = new List<string>();
    public List<string> pdfLinks = new List<string>();
    public List<string> videoLinks = new List<string>();
    public List<string> glbLinks = new List<string>();
    public static ApiConnection instance;
    public GameObject imageItem, videoItem;
    public GameObject pdfItem;

    void Start()
    {
        instance = this;
        //  StartCoroutine(FetchFiles());
      //  StartCoroutine(jobs());
      StartCoroutine(  webservice.instance.GetInfoRequest(jobs));

    }
    public void jobs(GetInfoResponse data) 
    {
        Debug.Log("getInfoCall");
            if (data != null)
            {
                foreach (var img in data.images)
                {
                    GameObject item = Instantiate(imageItem, imageItem.transform.parent);
                    item.name = imageLinks.Count.ToString();
                    item.SetActive(true);

                    StartCoroutine(LoadImage(item.GetComponentInChildren<RawImage>(), "http://194.62.43.230:8000/" + img.image));

                item.GetComponentInChildren<RTLTextMeshPro>().text = img.name;
                imageLinks.Add(img.image);
                    Debug.Log("Image: " + img.image);
                }

                foreach (var pdf in data.pdfs)
                {
                    print("PDF: " + pdf.pdf);
                GameObject item = Instantiate(pdfItem, pdfItem.transform.parent);
                item.name = pdfLinks.Count.ToString();

                item.GetComponentInChildren<RTLTextMeshPro>().text = pdf.name;
                item.SetActive(true);
           //     StartCoroutine(LoadImage(item.GetComponentInChildren<RawImage>(), "http://194.62.43.230:8000/" + pdf.pdf));
                pdfLinks.Add(pdf.pdf);
               // Debug.Log("Image: " + pdf.pdf);
            }

                foreach (var video in data.videos)
                {
                    GameObject item = Instantiate(videoItem, videoItem.transform.parent);
                    item.name = videoLinks.Count.ToString();
                    item.SetActive(true);
                item.GetComponentInChildren<RTLTextMeshPro>().text = video.name;
                    videoLinks.Add("http://194.62.43.230:8000/" + video.video);
                    Debug.Log("Video: " + video.video);
                }

                foreach (var glb in data.glbs)
                {
                    Debug.Log("GLB: " + glb.glb);
                    glbLinks.Add("http://194.62.43.230:8000/" + glb.glb);
                    // Store the first GLB URL in PlayerPrefs for avatar use
                    if (glbLinks.Count == 1)
                    {
                        PlayerPrefs.SetString("profile_glb", "http://194.62.43.230:8000/" + glb.glb);
                        PlayerPrefs.Save();
                    }
                }
            }
        
    }

    IEnumerator FetchFiles()
    {
        using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                ApiResponse response = JsonUtility.FromJson<ApiResponse>(request.downloadHandler.text);
                CategorizeFiles(response.data);
            }
            else
            {
                Debug.LogError("Error fetching data: " + request.error);
            }
        }
    }

    void CategorizeFiles(List<FileData> files)
    {
        foreach (var file in files)
        {
            if (file.type == "0")
            {
                // برای تصاویر
                GameObject item = Instantiate(imageItem, imageItem.transform.parent);
                item.name = imageLinks.Count.ToString();
                item.SetActive(true);
                StartCoroutine(LoadImage(item.GetComponentInChildren<RawImage>(), file.link));
                imageLinks.Add(file.link);
            }
            else if (file.type == "1")
            {
                // برای ویدیوها
                GameObject item = Instantiate(videoItem, videoItem.transform.parent);
                item.name = videoLinks.Count.ToString();
                item.SetActive(true);
                videoLinks.Add(file.link);

                // گرفتن پیش‌نمایش از فریم 100 ویدیو
             //   StartCoroutine(LoadVideoPreview(item.GetComponentInChildren<RawImage>(), file.link));
            }
        }

        Debug.Log("Images: " + string.Join(", ", imageLinks));
        Debug.Log("Videos: " + string.Join(", ", videoLinks));
    }

    private IEnumerator LoadImage(RawImage r, string url)
    {
        using (UnityWebRequest request = UnityWebRequestTexture.GetTexture(url))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
                r.texture = texture;
            }
            else
            {
                Debug.LogError("Error loading image: " + request.error);
            }
        }
    }

    private IEnumerator LoadVideoPreview(RawImage r,string url)
    {
        VideoPlayer videoPlayer = new GameObject("VideoPlayer").AddComponent<VideoPlayer>();
        videoPlayer.url = url;
        videoPlayer.renderMode = VideoRenderMode.APIOnly;
        videoPlayer.isLooping = false;

        // یک RenderTexture برای ذخیره فریم ویدیو
        RenderTexture renderTexture = new RenderTexture(1920, 1080, 24); // ابعاد تصویر ویدیو
        videoPlayer.targetTexture = renderTexture;

        // آماده‌سازی و پخش ویدیو
        videoPlayer.Prepare();

        // صبر کنید تا ویدیو آماده شود
        while (!videoPlayer.isPrepared)
        {
            yield return null;
        }

        // تنظیم زمان پخش به فریم 100
        videoPlayer.time = (0 / videoPlayer.frameRate); // به زمان معادل فریم 100 تنظیم می‌کنیم
        videoPlayer.Play();

        // صبر کنید تا فریم مشخص شده پخش شود
        yield return new WaitForSeconds(0.1f);

        // گرفتن تصویر از RenderTexture
        Texture2D texture = new Texture2D(1920, 1080); // ابعاد تصویر ویدیو
        RenderTexture.active = renderTexture;
        texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture.Apply();

        // نمایش فریم به‌عنوان پیش‌نمایش ویدیو
        r.texture = texture;

        // توقف ویدیو پس از گرفتن فریم
        videoPlayer.Stop();
        Destroy(videoPlayer.gameObject); // حذف VideoPlayer پس از اتمام کار
    }
}
