using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.Networking;
using UnityEngine.UI;
using TMPro;
public class AssetBundleLoader : MonoBehaviour
{
  [Header("UI Elements")]
    public TMP_Text progressText;

    [Header("Download Settings")]
    public string fbxUrl = "http://yourserver.com/path/to/model.fbx"; // Replace with your actual FBX URL
    public string savePath = "Assets/DownloadedModels/model.fbx"; // Path to save the downloaded FBX file
    public int maxRetries = 3; // Maximum number of retries

    private int currentRetries = 0;

    void Start()
    {
        if (progressText != null)
        {
            progressText.text = "0%";
            progressText.gameObject.SetActive(true);
        }

        // Start downloading the FBX file automatically
        StartCoroutine(DownloadFBXFile());
    }

    IEnumerator DownloadFBXFile()
    {
        while (currentRetries < maxRetries)
        {
            using (UnityWebRequest uwr = UnityWebRequest.Get(fbxUrl))
            {
                uwr.SendWebRequest();

                while (!uwr.isDone)
                {
                    float progress = Mathf.Clamp01(uwr.downloadProgress);
                    if (progressText != null)
                        progressText.text = $"{(progress * 100f):0.0}%";
                    yield return null;
                }

                if (uwr.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Download failed: " + uwr.error);

                    // Retry logic
                    currentRetries++;
                    if (currentRetries < maxRetries)
                    {
                        Debug.Log("Retrying download... Attempt " + currentRetries);
                        progressText.text = $"Retrying... ({currentRetries}/{maxRetries})";
                        yield return new WaitForSeconds(2f); // Wait before retrying
                    }
                    else
                    {
                        Debug.LogError("Max retries reached. Download failed.");
                        progressText.text = "Download failed!";
                    }
                }
                else
                {
                    // Successful download
                    byte[] downloadedData = uwr.downloadHandler.data;
                    SaveFBXFile(downloadedData);

                    if (progressText != null)
                        progressText.text = "Download complete!";
                    break; // Exit the loop if download is successful
                }
            }
        }
    }

    void SaveFBXFile(byte[] data)
    {
        // Ensure directory exists
        string directory = Path.GetDirectoryName(savePath);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        // Write the downloaded data to the specified path
        File.WriteAllBytes(savePath, data);
        Debug.Log("FBX file saved to: " + savePath);
    }
}