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

public class StreamingAssetsHelper
{
	/*
	/// <summary>
	/// 同步读取 
	/// Android下 只适合读取文本非常少的情况
	/// </summary>
	/// <returns>The all text.</returns>
	/// <param name="file">File.</param>
	public static string ReadAllText (string path)
	{
	}

	private static string ReadAllTextForiOS (string path)
	{
		if (File.Exists(path))
		{
			return File.ReadAllText(path);
		}
		else
		{
			GameDebug.LogError("StreamingAsset File not found at: " + path);
			return null;
		}
	} 

	private static string ReadAllTextForAndroid (string path)
	{
		// 标识未完成
		bool hasCompleted = false;

		// 构造请求
		UnityWebRequest request = new UnityWebRequest(path);
		// 异步发送
		UnityWebRequestAsyncOperation opt = request.SendWebRequest();

		// 回调
		opt.completed += (AsyncOperation obj) => 
		{
			// 标识完成
			hasCompleted = true;
		};

		// 未完成则一直等待
		while (!hasCompleted)
		{
			Thread.Yield();
		}

		if (request.isDone)
		{
			if (string.IsNullOrEmpty(request.error))
			{
				// success
				return "";
			}
			else
			{
				// fail
				GameDebug.LogError(request.error);
				return null;
			}
		}
		else
		{
			GameDebug.LogError("代码异常, UnityWebRequest 未完成: " + request.error);
			return null;
		}
	}
	*/

	public static void Copy (string src, string dst, Action onSuccess, Action<string> onFail)
    {
        src = src.Trim();
        dst = dst.Trim();

        try
        {
            if (File.Exists(dst))
                File.Delete(dst);
        }
        catch (Exception e)
        {
            GameDebug.LogError(e);
        }

        // 判断目标文件夹是否存在
        if (Application.isEditor)
        {
            //GameDebug.Log("编辑器跳过拷贝操作");
            if (File.Exists(src))
                File.Copy(src, dst);

            if (onSuccess != null)
            {
                onSuccess();
            }
            return;
        }

        string dstFolder = System.IO.Path.GetDirectoryName(dst);
        if (!Directory.Exists(dstFolder))
            Directory.CreateDirectory(dstFolder);

        GameDebug.Log(string.Format("StreamingAssetsHelper [src: {0}] -> [dst: {1}]", src, dst));

		if (Application.platform == RuntimePlatform.Android)
		{
			Copy_Android(src, dst, onSuccess, onFail);
		}
		else
		{
			Copy_NotAndroid(src, dst, onSuccess, onFail);
		}
	}

	private static void Copy_NotAndroid (string src, string dst, Action onSuccess, Action<string> onFail)
	{
		// 线程避免拷贝大文件导致界面假死
		ThreadStart action = delegate 
		{
			Copy_Thread_NotAndroid(src, dst, onSuccess, onFail);
		};

		Thread t = new Thread(action);
		t.Start();
	}

	private static void Copy_Thread_NotAndroid (string src, string dst, Action onSuccess, Action<string> onFail)
	{
		try
		{
			File.Copy(src, dst, true);

			if (onSuccess != null)
			{
				
				UnityThread.PostAction(onSuccess);
			}
		}
		catch(Exception e)
		{
			if (onFail != null)
			{
				Action action = delegate {
					onFail(e.Message);
				};
				UnityThread.PostAction(action);
			}
		}
	}

	static void Copy_Android (string src, string dst, Action onSuccess, Action<string> onFail)
	{


		try
		{
			UnityWebRequest request = new UnityWebRequest(src);
			request.downloadHandler = new DownloadHandlerFile(dst);

			UnityWebRequestAsyncOperation opt = request.SendWebRequest();
			opt.completed += (AsyncOperation obj) => 
			{
				if (string.IsNullOrEmpty(request.error) && request.isDone)
				{
					// success
					if (onSuccess != null)
					{
						onSuccess();
					}
				}
				else
				{
					// fail
					if (onFail != null)
					{
						onFail(request.error);
					}
				}
			};
		}
		catch (Exception ex)
		{
			if (onFail != null)
			{
				onFail(ex.Message);
			}
		}
	}
}
