using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using hirdParty.DownloadSystem;
using UnityEngine;

namespace ThirdParty.DownloadSystem
{
    public class CheckFilePool : IDisposable, ICheckUpdate
    {
        public List<MD5FileInfo> CheckFile = new List<MD5FileInfo>();
        public System.Action OnFinish;
        public List<MD5FileInfo> shiBaiFile = new List<MD5FileInfo>();
        private List<CheckFileThran> _checkFileThrans = new List<CheckFileThran>();
        public bool _isStart;
        private int _maxCount;

        public bool isFinish;
        public string streamingAssetsPath;
        public bool isStreamingAssetsPath;

        private bool isRendCheckStreamingAssetsPath;
        private bool isLoadAllFinish;


        private string rootPath;
        public int FileCount()
        {
            lock (shiBaiFile)
            {
                int count = CheckFile.Count;
                return _maxCount - count;
            }
        }

        public void Start(string dPath, List<MD5FileInfo> CheckFile)
        {
            this.CheckFile = CheckFile;
            _maxCount = CheckFile.Count;
            isRendCheckStreamingAssetsPath = true;
            isLoadAllFinish = false;
            this.rootPath = dPath;
            for (int i = 0; i < 4; i++)
            {
                CheckFileThran checkFileThran = new CheckFileThran();
                checkFileThran.OnClick = Finish;
                checkFileThran.Start(dPath, this);
                _checkFileThrans.Add(checkFileThran);
            }

            FileDownloadSystem.Instance.AddCheckUpdate(this);
        }

        public void Update()
        {
        }

        private void Finish()
        {
            lock (_checkFileThrans)
            {
                for (int i = 0; i < _checkFileThrans.Count; i++)
                {
                    if (!_checkFileThrans[i].isEnd)
                    {
                        return;
                    }
                }

                try
                {
                    shiBaiFile.Clear();
                    for (int i = 0; i < _checkFileThrans.Count; i++)
                    {
                        shiBaiFile.AddRange(_checkFileThrans[i].shiBaiFile);
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }

            shiBaiFile.Clear();
            List<MD5FileInfo> fileInfo = new List<MD5FileInfo>();
            for (int i = 0; i < _checkFileThrans.Count; i++)
            {
                fileInfo.AddRange(_checkFileThrans[i].shiBaiFile);
            }

            isLoadAllFinish = true;
            shiBaiFile.AddRange(fileInfo);
        }


        private void CheckFileFinish()
        {
            OnFinish?.Invoke();
            isFinish = true;
            OnFinish = null;
        }

        private void CheckLoadFlie(List<MD5FileInfo> fileInfo)
        {
            int count = fileInfo.Count;
            if (count <= 0)
            {
                CheckFileFinish();
                return;
            }

            for (int i = 0; i < fileInfo.Count; i++)
            {
                MD5FileInfo md5FileInfo = fileInfo[i];
                DownloadFileData downloadFileData = new DownloadFileData();
                downloadFileData.remoteUrl =
                    streamingAssetsPath  + md5FileInfo.fileName;
                Debug.Log("下载文件" + downloadFileData.remoteUrl);
                DownloadHander fileDow = FileDownloadSystem.Instance.DownloadFile(downloadFileData);
                fileDow.OnFinishCallBack = delegate(DownloadHander hander)
                {
                    byte[] data = hander.Data;
                    count--;
                    string md5 = FileMD5(data);

                    if (!md5FileInfo.md5.Equals(md5))
                    {
                        Debug.Log("MD5校验失败" + downloadFileData.remoteUrl);
                        shiBaiFile.Add(md5FileInfo);
                    }
                    else
                    {
                        string rp = rootPath + md5FileInfo.fileName;
                        File.WriteAllBytes(rp,data);
                        Debug.Log("拷贝文件到" +rp);
                    }

                    if (count <= 0)
                    {
                        CheckFileFinish();
                    }
                };
            }
        }

        public static string FileMD5(byte[] data)
        {
            if (data == null)
            {
                return "";
            }

            byte[] retVal = null;
            MD5 md5 = new MD5CryptoServiceProvider();
            retVal = md5.ComputeHash(data);

            return ByteArrayToString(retVal);
        }

        public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
            {
                hex.AppendFormat("{0:x2}", b);
            }

            return hex.ToString();
        }

        public void Dispose()
        {
            FileDownloadSystem.Instance.RemvoeCheckUpdate(this);
        }

        public void CheckUpdate()
        {
            if (!isLoadAllFinish)
            {
                return;
            }
            if (isRendCheckStreamingAssetsPath && isStreamingAssetsPath && shiBaiFile.Count > 0)
            {
                List<MD5FileInfo> fileInfo = new List<MD5FileInfo>();
                fileInfo.AddRange(shiBaiFile);
                shiBaiFile.Clear();
                CheckLoadFlie(fileInfo);
                isRendCheckStreamingAssetsPath = false;
                FileDownloadSystem.Instance.RemvoeCheckUpdate(this);
            }
            else
            {
                CheckFileFinish();
                FileDownloadSystem.Instance.RemvoeCheckUpdate(this);
            }
        }
    }
}