using Newtonsoft.Json;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

public class JsonDataService : IDataService
{
    public bool SaveData<T>(string relativePath, T data, bool encrypted)
    {
        string path = Application.persistentDataPath + relativePath;
        try
        {
            string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
            if (encrypted)
            {
                jsonData = EncryptDecrypt(jsonData);
            }
            using (FileStream stream = new FileStream(path, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(jsonData);
                }
            }
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to save data: {e.Message}");
            return false;
        }
    }

    public T LoadData<T>(string relativePath, bool encrypted)
    {
        string path = Application.persistentDataPath + relativePath;
        if (!File.Exists(path))
        {
            throw new FileNotFoundException($"Cannot load file at {path}. File does not exist!");
        }

        try
        {
            string jsonData = "";
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    jsonData = reader.ReadToEnd();
                }
            }

            if (encrypted)
            {
                jsonData = EncryptDecrypt(jsonData);
            }

            return JsonConvert.DeserializeObject<T>(jsonData);
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to load data: {e.Message}");
            throw;
        }
    }

    private string EncryptDecrypt(string data)
    {
        // Simple XOR encryption (replace with more secure method for production)
        string key = "YOUR_ENCRYPTION_KEY";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            result.Append((char)(data[i] ^ key[i % key.Length]));
        }
        return result.ToString();
    }
} 