using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;

namespace TFramework
{
    public static class ImprotPackageManager
    {
        static ListRequest _listRequest;
        static List<string> _allPackageName = new List<string>();

        public static PackageConfig packageConfig;

        private static TAction onChekOver;

        public static void CheckImportPackage(TAction chekOverEvent = null)
        {
            packageConfig = AssetDatabase.LoadAssetAtPath<PackageConfig>(EditorConfigFile.PACKAGECONFIG);
            if (packageConfig == null|| packageConfig.packageNams.Count <= 0) return;
            _listRequest = Client.List();
            onChekOver = chekOverEvent;
            EditorApplication.update += Update;
        }

        private static void Update()
        {
            if(_listRequest.IsCompleted)
            {
                if(_listRequest.Status==StatusCode.Success)
                {
                    _allPackageName.Clear();
                    foreach (var package in _listRequest.Result)
                    {
                        _allPackageName.Add(package.name);
                    }
                    foreach (var item in packageConfig.packageNams)
                    {
                        if(_allPackageName.Find(p=>p==item)==null)
                        {
                            AddRequest addRequest = Client.Add(item);
                            while(!addRequest.IsCompleted)
                            {
                                if (addRequest.Status == StatusCode.InProgress)
                                    Debug.Log(addRequest.Status);
                                else
                                {
                                    Debug.Log($"安装依赖插件包{item}出错");
                                    break;
                                }
                            }
                            if(addRequest.IsCompleted)
                            {
                                if (addRequest.Status >= StatusCode.Failure)
                                    Debug.Log(addRequest.Error.message);
                            }
                        }
                    }
                }
                else if(_listRequest.Status >= StatusCode.Failure)
                    Debug.Log(_listRequest.Error.message);

                onChekOver?.Invoke();
                EditorApplication.update -= Update;
            }
        }
    }
}
