using Godot;
using System;
using System.Text.Json;

using AvatarDoll;

public partial class AvatarDollAdapter : Node
{
    private static AvatarDollAdapter _instance;
    
    public static AvatarDollAdapter Instance
    {
        get
        {
            if (_instance == null)
            {
                GD.Print("AvatarDollAdapter instance is null!");
            }
            return _instance;
        }
    }

    private AvatarDollData data;
    
    public override void _Ready()
    {
        if (_instance == null)
        {
            _instance = this;
            // 确保单例在场景切换时不被销毁
            // GetTree().Root.AddChild(this);
            Owner = GetTree().Root;
            GD.Print("C# AvatarDollAdapter initialized");
        }
        else
        {
            QueueFree();
        }
    }

    public void LoadJson(string jsonPath)
    {
        using var file = FileAccess.Open(jsonPath, FileAccess.ModeFlags.Read);
        string jsonString = file.GetAsText();
        data = JsonSerializer.Deserialize<AvatarDollData>(jsonString);
    }

    public void SaveJson(string jsonPath)
    {
        using var file = FileAccess.Open(jsonPath, FileAccess.ModeFlags.Write);
        string jsonString = JsonSerializer.Serialize(data);
        file.StoreString(jsonString);
    }
    
    public void ParseJson(string jsonPath, string jsonString2)
    {
        using var file = FileAccess.Open(jsonPath, FileAccess.ModeFlags.Read);
        string jsonString1 = file.GetAsText();
        AvatarDollData deData1 = JsonSerializer.Deserialize<AvatarDollData>(jsonString1);
        AvatarDollData deData2 = JsonSerializer.Deserialize<AvatarDollData>(jsonString2);
        string jsonString3 = JsonSerializer.Serialize(deData1);
        string jsonString4 = JsonSerializer.Serialize(deData2);
        AvatarDollData deData3 = JsonSerializer.Deserialize<AvatarDollData>(jsonString3);
        AvatarDollData deData4 = JsonSerializer.Deserialize<AvatarDollData>(jsonString4);
        
        bool b2 = deData1.Equals(deData2);
        bool b3 = deData1.Equals(deData3);
        bool b4 = deData1.Equals(deData4);
        if (b2 && b3 && b4)
            GD.Print("Equals !!!!");
    }
    
}
