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


public class UnityWebHttpDownload : HttpDownloadBasic
{
    private UnityWebRequest _unityWebRequest;
    private UnityWebRequestAsyncOperation _unityWebRequestAsyncOperation;


    protected float currTime;

    protected override void ProStartDown()
    {
        maxCount--;
        isFinish = false;
        currTime = 0;
        if (_unityWebRequest != null)
        {
            _unityWebRequest.Dispose();
            _unityWebRequest = null;
        }

        _unityWebRequest = UnityWebRequest.Get(downloadFileData.remoteUrl);
        if (!string.IsNullOrEmpty(downloadFileData.localPath))
        {
            _unityWebRequest.downloadHandler = new DownloadHandlerFile(downloadFileData.localPath);
        }

        _unityWebRequest.timeout = timeOut;
        // _unityWebRequest.
        _unityWebRequestAsyncOperation = _unityWebRequest.SendWebRequest();
        DownloadHander.UnityWebRequestAsyncOperation = _unityWebRequestAsyncOperation;
    }

    protected override bool ProFinish()
    {
        return _unityWebRequestAsyncOperation.isDone;
    }

    public override bool AllFinish()
    {
        return isFinish;
    }

    public override UnityWebRequest.Result Result()
    {
        return _unityWebRequest.result;
    }

    public override void Update()
    {
        currTime += Time.deltaTime;
        if (!isFinish && ProFinish())
        {
            isFinish = true;
            if (_unityWebRequest.result != UnityWebRequest.Result.Success)
            {
                Debug.Log("下载失败" + _unityWebRequest.error + "   " + downloadFileData.remoteUrl);
                if (maxCount > 0)
                {
                    ProStartDown();
                }
                else
                {
                    DownloadHander.OnFinishCallBack?.Invoke(DownloadHander);
                }
            }
            else
            {
                DownloadHander.OnFinishCallBack?.Invoke(DownloadHander);
            }
        }
        else
        {
            if (currTime > timeOut)
            {
                Debug.Log("超时"+currTime+"__"+timeOut);
                ProStartDown();
            }
        }
    }
}