using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ScreenshotHelper : MonoBehaviour
{
    public static void Capture()
    {
        if (!Application.isPlaying)
        {
            UnityEngine.Debug.LogWarning("플레이 모드에서만 가능합니다.");
            return;
        }

        var go = new GameObject("ScreenshotHelper");
        go.hideFlags = HideFlags.HideAndDontSave;
        go.AddComponent<ScreenshotHelper>();
    }

    private void Start()
    {
        StartCoroutine(CaptureCoroutine());
    }

    private IEnumerator CaptureCoroutine()
    {
        yield return new WaitForEndOfFrame();

        string projectRoot = Path.GetDirectoryName(Application.dataPath);
        string screenshotFolder = Path.Combine(projectRoot, "ScreenShot");
        if (!Directory.Exists(screenshotFolder))
            Directory.CreateDirectory(screenshotFolder);

        string fileName = "Screenshot_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + ".png";
        string fullPath = Path.Combine(screenshotFolder, fileName);

        Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        tex.Apply();

        File.WriteAllBytes(fullPath, tex.EncodeToPNG());
        Destroy(tex);

        UnityEngine.Debug.Log($"[ScreenshotTool] 스크린샷 저장됨: {fullPath}");

        // Unity 다이얼로그 띄우기
        bool openFolder = EditorUtility.DisplayDialog(
            "스크린샷 저장 완료",
            $"{fileName}\n파일 위치를 여시겠습니까?",
            "예", "아니오");

        if (openFolder)
        {
            // 윈도우 탐색기 열기
            Process.Start("explorer.exe", $"/select,\"{fullPath}\"");
        }

        Destroy(gameObject);
    }
}

public static class ScreenshotTool
{
    [MenuItem("Tools/Take Screenshot (PlayMode) %#x")]
    public static void TakeScreenshotPlayMode()
    {
        ScreenshotHelper.Capture();
    }
}