using UnityEngine;
using UnityEditor;
using ZXing;
using ZXing.QrCode;
using System.IO;

public class QRCodeGenerator : EditorWindow
{
    // 입력 필드
    string animalName = "";
    int qrSize = 256;
    string savePath = "Assets/QRCodes";

    // 미리보기 텍스처
    Texture2D previewTex;

    [MenuItem("Tools/QR Code Generator")]
    public static void ShowWindow()
    {
        GetWindow<QRCodeGenerator>("QR Code Generator");
    }

    void OnGUI()
    {
        GUILayout.Label("QR Code Generator", EditorStyles.boldLabel);
        GUILayout.Space(10);

        // 동물 이름 입력
        animalName = EditorGUILayout.TextField("Animal Name", animalName);

        // QR 사이즈
        qrSize = EditorGUILayout.IntField("QR Size", qrSize);

        // 저장 경로
        savePath = EditorGUILayout.TextField("Save Path", savePath);

        GUILayout.Space(10);

        // 미리보기 생성
        if (GUILayout.Button("Preview"))
        {
            if (!string.IsNullOrEmpty(animalName))
                previewTex = GenerateQR(animalName, qrSize);
        }

        // PNG 저장
        if (GUILayout.Button("Generate & Save"))
        {
            if (!string.IsNullOrEmpty(animalName))
                SaveQR(animalName);
        }

        GUILayout.Space(10);

        // 미리보기 표시
        if (previewTex != null)
        {
            GUILayout.Label("Preview:");
            GUILayout.Label(previewTex, GUILayout.Width(256), GUILayout.Height(256));
        }
    }

    // QR Texture2D 생성
    Texture2D GenerateQR(string text, int size)
    {
        var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Width = size,
                Height = size,
                Margin = 1
            }
        };

        var pixels = writer.Write(text);
        var tex = new Texture2D(size, size);
        tex.SetPixels32(pixels);
        tex.Apply();
        return tex;
    }

    // PNG 저장
    void SaveQR(string text)
    {
        if (!Directory.Exists(savePath))
            Directory.CreateDirectory(savePath);

        var tex = GenerateQR(text, qrSize);
        var bytes = tex.EncodeToPNG();
        var path = $"{savePath}/{text}_QR.png";

        File.WriteAllBytes(path, bytes);
        AssetDatabase.Refresh();

        Debug.Log($"QR 저장 완료: {path}");
        previewTex = tex;
    }
}