using UnityEngine;
using System.Collections.Generic;
using System.IO;

public class ImageGalleryManager : MonoBehaviour
{
    public static ImageGalleryManager Instance;

    private string persistentPath;
    private List<Texture2D> loadedFaces = new List<Texture2D>();

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);

        persistentPath = Application.persistentDataPath + "/FaceInvaders/Faces/";

        if (!Directory.Exists(persistentPath))
            Directory.CreateDirectory(persistentPath);

        LoadFacesFromStorage();
    }

    public void LoadFacesFromStorage()
    {
        loadedFaces.Clear();
        if (!Directory.Exists(persistentPath)) return;

        string[] files = Directory.GetFiles(persistentPath, "*.png");
        foreach (string file in files)
        {
            Texture2D texture = LoadTextureFromFile(file);
            if (texture != null)
                loadedFaces.Add(texture);
        }
        Debug.Log("Loaded " + loadedFaces.Count + " faces from storage");
    }

    public List<Texture2D> GetFaces()
    {
        return loadedFaces;
    }

    public void SaveFaceFromPath(string imagePath)
    {
        if (!File.Exists(imagePath))
        {
            Debug.LogError("Image file not found: " + imagePath);
            return;
        }
        string fileName = Path.GetFileName(imagePath);
        string destPath = persistentPath + fileName;
        File.Copy(imagePath, destPath, true);
        Debug.Log("Face saved: " + destPath);
        LoadFacesFromStorage();
    }

    public void ClearAllFaces()
    {
        if (Directory.Exists(persistentPath))
        {
            Directory.Delete(persistentPath, true);
            Directory.CreateDirectory(persistentPath);
        }
        loadedFaces.Clear();
        Debug.Log("All faces cleared");
    }

    private Texture2D LoadTextureFromFile(string path)
    {
        try
        {
            byte[] fileData = File.ReadAllBytes(path);
            Texture2D texture = new Texture2D(1, 1);
            texture.LoadImage(fileData);
            return texture;
        }
        catch (System.Exception ex)
        {
            Debug.LogError("Error loading texture: " + ex.Message);
            return null;
        }
    }
}
