using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using AssetBank.Settings;
using System.Collections.Generic;

namespace AssetBank.Editor.Tools
{
    public static class ScriptExporter
    {
        [MenuItem("Tools/Exporter/Export Scripts")]
        public static void ExportScripts()
        {
            ProcessAndCopyScripts();
        }

        public static void ProcessAndCopyScripts(string destinationPath = null)
        {
            var settings = ProjectExporterSettings.GetOrCreateSettings();
            var foldersToIgnore = settings.FoldersToIgnore;
            var scriptGuids = AssetDatabase.FindAssets("t:Script", new[] { "Assets" });
            
            var filteredScriptPaths = new List<string>();
            foreach (var guid in scriptGuids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                
                var directoryName = Path.GetDirectoryName(path);
                if (foldersToIgnore.Any(folder => directoryName != null && directoryName.StartsWith(folder, StringComparison.OrdinalIgnoreCase))) continue;
                
                filteredScriptPaths.Add(path);
            }
            
            destinationPath ??= EditorUtility.SaveFolderPanel("Choose destination to copy scripts into", Application.dataPath, "");
            if (string.IsNullOrEmpty(destinationPath)) return;

            foreach (var scriptPath in filteredScriptPaths)
            {
                CopyFile(scriptPath, destinationPath);
            }
        }

        private static void CopyFile(string sourcePath, string targetDir)
        {
            var relativePath = Path.GetRelativePath(Application.dataPath, sourcePath);
            var targetPath = Path.Combine(targetDir, relativePath);
            var dirName = Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(dirName))
            {
                if (dirName != null) Directory.CreateDirectory(dirName);
            }
            File.Copy(sourcePath, targetPath, true);
        }
    }
}