using UnityEngine;
using UnityEditor;
using System.IO;
using UniHumanoid;

public class HumanPoseClipCreator : EditorWindow
{
    private Animator selectedAnimator;
    private string assetName = "NewPoseClip";
    private string savePath = "Assets/Resources";

    [MenuItem("Tools/Animation/Create Human Pose Clip")]
    public static void ShowWindow()
    {
        GetWindow<HumanPoseClipCreator>("Human Pose Clip Creator");
    }

    private void OnGUI()
    {
        GUILayout.Label("Create Human Pose Clip", EditorStyles.boldLabel);
        
        EditorGUILayout.Space();
        
        selectedAnimator = (Animator)EditorGUILayout.ObjectField("Target Animator", selectedAnimator, typeof(Animator), true);
        
        EditorGUILayout.Space();
        
        assetName = EditorGUILayout.TextField("Asset Name", assetName);
        
        EditorGUILayout.BeginHorizontal();
        savePath = EditorGUILayout.TextField("Save Path", savePath);
        if (GUILayout.Button("Browse", GUILayout.Width(60)))
        {
            string path = EditorUtility.SaveFolderPanel("Select Save Location", "Assets", "");
            if (!string.IsNullOrEmpty(path))
            {
                string projectPath = Application.dataPath;
                if (path.StartsWith(projectPath))
                {
                    savePath = "Assets" + path.Substring(projectPath.Length);
                }
                else
                {
                    EditorUtility.DisplayDialog("Error", "Please select a folder inside the Assets directory!", "OK");
                }
            }
        }
        EditorGUILayout.EndHorizontal();
        
        EditorGUILayout.Space();
        
        GUI.enabled = selectedAnimator != null;
        if (GUILayout.Button("Create Pose Clip"))
        {
            CreatePoseClip();
        }
        GUI.enabled = true;
    }

    private void CreatePoseClip()
    {
        if (selectedAnimator == null)
        {
            EditorUtility.DisplayDialog("Error", "Please select an Animator first!", "OK");
            return;
        }

        // 경로가 Assets로 시작하는지 확인
        if (!savePath.StartsWith("Assets/"))
        {
            EditorUtility.DisplayDialog("Error", "Save path must start with 'Assets/'!", "OK");
            return;
        }

        var animator = selectedAnimator;
        var avatar = animator.avatar;
        
        if (avatar == null || !avatar.isHuman)
        {
            EditorUtility.DisplayDialog("Error", "Selected Animator must have a Humanoid Avatar!", "OK");
            return;
        }

        try
        {
            // HumanPoseHandler를 사용하여 현재 포즈 가져오기
            var handler = new HumanPoseHandler(avatar, animator.transform);
            HumanPose pose = new HumanPose();
            handler.GetHumanPose(ref pose);

            // 새로운 HumanPoseClip 생성
            HumanPoseClip poseClip = ScriptableObject.CreateInstance<HumanPoseClip>();
            poseClip.ApplyPose(ref pose);

            // 저장 경로 생성
            string fullPath = Path.Combine(savePath, $"{assetName}.pose.asset");
            string directory = Path.GetDirectoryName(fullPath);
            
            // 디렉토리가 없으면 생성
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // 에셋 저장
            AssetDatabase.CreateAsset(poseClip, fullPath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            Debug.Log($"Pose clip has been created at: {fullPath}");
            EditorUtility.DisplayDialog("Success", $"Pose clip has been created at: {fullPath}", "OK");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"Error creating pose clip: {e.Message}");
            EditorUtility.DisplayDialog("Error", $"Failed to create pose clip: {e.Message}", "OK");
        }
    }
} 