#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;

public class SpriteSlicer : EditorWindow {
  private Vector2Int cellSize = new Vector2Int(32, 32);
  private FilterMode filterMode = FilterMode.Point;

  [MenuItem("Tools/Slice Selected Sprites")]
  public static void ShowWindow() {
    GetWindow<SpriteSlicer>("Sprite Slicer");
  }

  private void OnGUI() {
    GUILayout.Label("Slice Settings", EditorStyles.boldLabel);

    cellSize = EditorGUILayout.Vector2IntField("Cell Size", cellSize);
    filterMode = (FilterMode)EditorGUILayout.EnumPopup("Filter Mode", filterMode);

    if (GUILayout.Button("Slice and Apply")) {
      SliceSelectedSprites(cellSize, filterMode);
    }
  }

  private static void SliceSelectedSprites(Vector2Int cellSize, FilterMode mode) {
    var textures = Selection.GetFiltered<Texture2D>(SelectionMode.DeepAssets);

    foreach (Texture2D texture in textures) {
      string path = AssetDatabase.GetAssetPath(texture);
      TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;

      if (importer != null) {
        importer.textureType = TextureImporterType.Sprite;
        importer.spriteImportMode = SpriteImportMode.Multiple;
        importer.filterMode = mode;

        int columns = texture.width / cellSize.x;
        int rows = texture.height / cellSize.y;

        SpriteMetaData[] metas = new SpriteMetaData[columns * rows];
        int index = 0;

        for (int y = rows - 1; y >= 0; y--) {
          for (int x = 0; x < columns; x++) {
            SpriteMetaData meta = new SpriteMetaData();
            meta.name = texture.name + "_" + index;
            meta.rect = new Rect(x * cellSize.x, y * cellSize.y, cellSize.x, cellSize.y);
            meta.pivot = new Vector2(0.5f, 0.5f);
            meta.alignment = (int)SpriteAlignment.Center;
            metas[index++] = meta;
          }
        }

        importer.spritesheet = metas;
        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
      }
    }

    Debug.Log("Slicing complete.");
  }
}
#endif
