using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using TMPro;
using UnityEngine;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using UnityEngine.UI;

public class exportUI : MonoBehaviour
{

    public exportToServer ExportToServer;

    private void Awake()
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

    }


    private string CreateMD5(string input)
    {
        // Use input string to calculate MD5 hash
        using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
        {
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }

    private Dictionary<string, int> GameObjectNamesCache = new Dictionary<string, int>();


    private Dictionary<string, string> SpritesDictionary = new Dictionary<string, string>();
    private Dictionary<string, int> SpritesPPUDictionary = new Dictionary<string, int>();
    private Dictionary<string, Vector4> SpritesBorderDictionary = new Dictionary<string, Vector4>();

    private int currentPrefabID = 1;

    private void cacheGameObjectName(GameObject go)
    {
        string name = go.name;

        if (!GameObjectNamesCache.ContainsKey(name))
        {
            //doesn't exist
            GameObjectNamesCache[name] = currentPrefabID;
            currentPrefabID += 1;
        }
        return;
    }

    // Start is called before the first frame update
    void Start()
    {

        string json = "{\"prefabs\":";

        string childrenList = TraverseAllChildren(transform);

        json += childrenList;

        //textMeshProString.text = json;

        json += ",\"images\":[";

        foreach (KeyValuePair<string, string> keyValue in SpritesDictionary)
        {
            //childComponentsJson += "\"border\":[" + border.x + "," + border.y + "," + border.z + "," + border.w + "],";
            json += "{\"hash\":\"" + keyValue.Key + "\",\"base64\":\"" + keyValue.Value + "\",";

            if (SpritesBorderDictionary.ContainsKey(keyValue.Key))
            {
                Vector4 border = SpritesBorderDictionary[keyValue.Key];
                json += "\"border\":[" + border.x + "," + border.y + "," + border.z + "," + border.w + "],";
            }

            if (SpritesPPUDictionary.ContainsKey(keyValue.Key))
            {
                json += "\"ppu\":" + SpritesPPUDictionary[keyValue.Key] + ",";
            }

            json += "},";
        }

        json += "]";

        json += ",\"links\":{";
         foreach (KeyValuePair<string, int> keyValue in GameObjectNamesCache)
        {
            json += "\""+ keyValue.Value + "\":\"" + keyValue.Key + "\",";
            //Debug.Log("\"" + keyValue.Value + "\":\"" + keyValue.Key + "\",");
            //json += ",";
        }

        json += "}";
        json += "}";


        //Debug.Log(json);

        JObject jsonParse = JObject.Parse(json);
        string jsonString = JsonConvert.SerializeObject(jsonParse);

        byte[] compressedString = CompressString(jsonString);

        string brotliProject = Convert.ToBase64String(compressedString);

        //textMeshProString.text = brotliProject;

        ExportToServer.StartUpload("uiBrotli", brotliProject);

        //Debug.Log(jsonString);

    }

    private byte[] CompressString(string str)
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(str);
        using (var outputStream = new MemoryStream())
        {
            using (var brotliStream = new BrotliStream(outputStream, System.IO.Compression.CompressionLevel.Optimal))
            {
                brotliStream.Write(inputBytes, 0, inputBytes.Length);
            }
            return outputStream.ToArray();
        }
    }

    private string TextMeshProUGUIToComponent(TextMeshProUGUI _TextMeshPro)
    {

        string childComponentsJson = "";

        childComponentsJson += "{\"type\":\"TextMeshPro\",";

        childComponentsJson += "\"text\":\"" + _TextMeshPro.text + "\",";


        childComponentsJson += "\"color\":[" + (int)(_TextMeshPro.color.r * 255f) + "," + (int)(_TextMeshPro.color.g * 255f) + "," + (int)(_TextMeshPro.color.b * 255f) + "," + (int)(_TextMeshPro.color.a * 255f) + "],";


        // Get the current fontStyle
        FontStyles currentStyles = _TextMeshPro.fontStyle;


        string styles = "[";

        // Iterate through each style in the FontStyles enum
        foreach (FontStyles style in System.Enum.GetValues(typeof(FontStyles)))
        {
            // Check if the style is enabled using a bitwise AND
            if ((currentStyles & style) == style)
            {
                styles += "\""+style + "\",";
            }
        }

        styles += "]";


        if (styles != "[]")
        {
            //Debug.Log(styles);
            childComponentsJson += "\"fontStyles\":"+ styles + ",";

        }


        //childComponentsJson += "\"fontStyle\":\"" + _TextMeshPro.fontStyle. + "\",";


        //childComponentsJson += "\"text\":\"" + _TextMeshPro.text + "\",";

        childComponentsJson += "\"fontIndex\":" + Convert.ToInt32(_TextMeshPro.font.name) + ",";

        childComponentsJson += "\"fontSize\":" + _TextMeshPro.fontSize + ",";

        if (_TextMeshPro.enableAutoSizing == true)
        {

            childComponentsJson += "\"autoSizing\":1,";
            childComponentsJson += "\"fontSizeMin\":" + _TextMeshPro.fontSizeMin + ",";
            childComponentsJson += "\"fontSizeMax\":" + _TextMeshPro.fontSizeMax + ",";

        }

        if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Center)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "center" + "\",";
        }
        else if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Left)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "left" + "\",";
        }
        else if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Right)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "right" + "\",";
        }
        else if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Flush)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "flush" + "\",";
        }
        else if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Justified)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "justified" + "\",";
        }
        else if (_TextMeshPro.horizontalAlignment == HorizontalAlignmentOptions.Geometry)
        {
            childComponentsJson += "\"horizontalAlignment\":\"" + "geometry" + "\",";
        }

        if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Top)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "top" + "\",";
        }
        else if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Middle)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "middle" + "\",";
        }
        else if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Bottom)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "bottom" + "\",";
        }
        else if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Baseline)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "baseline" + "\",";
        }
        else if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Capline)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "capline" + "\",";
        }
        else if (_TextMeshPro.verticalAlignment == VerticalAlignmentOptions.Geometry)
        {
            childComponentsJson += "\"verticalAlignment\":\"" + "geometry" + "\",";
        }

        if (_TextMeshPro.enableWordWrapping == true)
        {
            childComponentsJson += "\"enableWordWrapping\":1,";
        }

        if (_TextMeshPro.overflowMode == TextOverflowModes.Overflow)
        {
            childComponentsJson += "\"overflowMode\":\"overflow\",";
        }
        else if (_TextMeshPro.overflowMode == TextOverflowModes.Truncate)
        {
            childComponentsJson += "\"overflowMode\":\"truncate\",";
        }


        //RectTransform _RectTransform = child.GetComponent<RectTransform>();


        //childComponentsJson += "\"sizeDelta\":[" + _RectTransform.sizeDelta.x + "," + _RectTransform.sizeDelta.y + "],";

        childComponentsJson += "}";
        return childComponentsJson;
    }


    private string ImageToComponent(Image _Image)
    {
        string childComponentsJson = "";

        childComponentsJson += "{\"type\":\"Image\",";

        string md5hash = "";



        if (_Image.sprite == null)
        {
            md5hash = "null";
        }
        else
        {


            if (_Image.raycastTarget == true)
            {
                childComponentsJson += "\"raycastTarget\":1,";
            }

            if (_Image.type == Image.Type.Simple)
            {
                childComponentsJson += "\"imageType\":\"simple\",";
            }
            else if (_Image.type == Image.Type.Sliced)
            {
                childComponentsJson += "\"imageType\":\"sliced\",";

                if (_Image.fillCenter == true)
                {
                    childComponentsJson += "\"fillCenter\":1,";
                }
                else
                {
                    childComponentsJson += "\"fillCenter\":0,";
                }
                childComponentsJson += "\"PPUM\":" + _Image.pixelsPerUnitMultiplier + ",";


            }
            else if (_Image.type == Image.Type.Filled)
            {
                childComponentsJson += "\"imageType\":\"filled\",";
            }
            else if (_Image.type == Image.Type.Tiled)
            {
                childComponentsJson += "\"imageType\":\"tiled\",";
            }

            if (_Image.sprite.name == "UISprite")
            {
                //no need to parse, just say that it's a UISprite
                md5hash = "UISprite";
            }else if (_Image.sprite.name == "InputFieldBackground")
            {
                md5hash = "InputFieldBackground";
            }
            else if (_Image.sprite.name == "Knob")
            {
                md5hash = "Knob";
            }
            else if (_Image.sprite.name == "Background")
            {
                md5hash = "Background";
            }
            else
            {
                string base64String = ConvertSpriteToBase64(_Image.sprite);
                md5hash = CreateMD5(base64String + (int)_Image.sprite.pixelsPerUnit).ToLower();
                //Debug.Log(base64String);

                if (!SpritesDictionary.ContainsKey(md5hash))
                {
                    //not yet exists
                    SpritesDictionary[md5hash] = base64String;
                }


                Vector4 border = _Image.sprite.border;

                if (border != Vector4.zero)
                {
                    SpritesBorderDictionary[md5hash] = border;
                }

                SpritesPPUDictionary[md5hash] = (int)_Image.sprite.pixelsPerUnit;
            }
        }


        childComponentsJson += "\"hash\":\"" + md5hash + "\",";



        if (_Image.color != null)
        {
            if (_Image.color.r != 1f ||
                _Image.color.g != 1f ||
                _Image.color.b != 1f ||
                _Image.color.a != 1f)
            {

                childComponentsJson += "\"color\":[" + (int)(_Image.color.r * 255f) + "," + (int)(_Image.color.g * 255f) + "," + (int)(_Image.color.b * 255f) + "," + (int)(_Image.color.a * 255f) + "],";
            }
        }

        childComponentsJson += "}";

        return childComponentsJson;
    }


    private string RectTransformToComponent(RectTransform _RectTransform)
    {
        string childComponentsJson = "";
        childComponentsJson += "{\"type\":\"RectTransform\",";

        childComponentsJson += "\"anchoredPosition\":[" + _RectTransform.anchoredPosition.x + "," + _RectTransform.anchoredPosition.y + "],";

        childComponentsJson += "\"sizeDelta\":[" + _RectTransform.sizeDelta.x + "," + _RectTransform.sizeDelta.y + "],";

        childComponentsJson += "\"anchorMin\":[" + _RectTransform.anchorMin.x + "," + _RectTransform.anchorMin.y + "],";
        childComponentsJson += "\"anchorMax\":[" + _RectTransform.anchorMax.x + "," + _RectTransform.anchorMax.y + "],";

        childComponentsJson += "\"offsetMin\":[" + _RectTransform.offsetMin.x + "," + _RectTransform.offsetMin.y + "],";
        childComponentsJson += "\"offsetMax\":[" + _RectTransform.offsetMax.x + "," + _RectTransform.offsetMax.y + "],";

        childComponentsJson += "\"pivot\":[" + _RectTransform.pivot.x + "," + _RectTransform.pivot.y + "],";


        childComponentsJson += "}";
        return childComponentsJson;
    }

    private string ContentSizeFitterToComponent(ContentSizeFitter _contentSizeFitter)
    {
        string childComponentsJson = "";
        childComponentsJson += "{\"type\":\"ContentSizeFitter\",";

        if (_contentSizeFitter.verticalFit == ContentSizeFitter.FitMode.Unconstrained)
        {
            childComponentsJson += "\"verticalFit\":\"Unconstrained\",";
        }else if (_contentSizeFitter.verticalFit == ContentSizeFitter.FitMode.MinSize)
        {
            childComponentsJson += "\"verticalFit\":\"MinSize\",";
        }
        else if (_contentSizeFitter.verticalFit == ContentSizeFitter.FitMode.PreferredSize)
        {
            childComponentsJson += "\"verticalFit\":\"PreferredSize\",";
        }

        if (_contentSizeFitter.horizontalFit == ContentSizeFitter.FitMode.Unconstrained)
        {
            childComponentsJson += "\"horizontalFit\":\"Unconstrained\",";
        }
        else if (_contentSizeFitter.horizontalFit == ContentSizeFitter.FitMode.MinSize)
        {
            childComponentsJson += "\"horizontalFit\":\"MinSize\",";
        }
        else if (_contentSizeFitter.horizontalFit == ContentSizeFitter.FitMode.PreferredSize)
        {
            childComponentsJson += "\"horizontalFit\":\"PreferredSize\",";
        }


        childComponentsJson += "}";
        return childComponentsJson;
    }


    private string HorizontalLayoutGroupToComponent(HorizontalLayoutGroup _horizontalLayout)
    {
        string childComponentsJson = "";
        childComponentsJson += "{\"type\":\"HorizontalLayoutGroup\",";

        childComponentsJson += "\"top\":"+ _horizontalLayout.padding.top + ",";
        childComponentsJson += "\"left\":" + _horizontalLayout.padding.left + ",";
        childComponentsJson += "\"right\":" + _horizontalLayout.padding.right + ",";
        childComponentsJson += "\"bottom\":" + _horizontalLayout.padding.bottom + ",";

        childComponentsJson += "\"spacing\":" + _horizontalLayout.spacing + ",";

        if (_horizontalLayout.reverseArrangement == true)
        {
            childComponentsJson += "\"reverseArrangement\":1,";
        }

        if (_horizontalLayout.childControlWidth == true)
        {
            childComponentsJson += "\"childControlWidth\":1,";
        }

        if (_horizontalLayout.childControlHeight == true)
        {
            childComponentsJson += "\"childControlHeight\":1,";
        }

        if (_horizontalLayout.childScaleWidth == true)
        {
            childComponentsJson += "\"childScaleWidth\":1,";
        }

        if (_horizontalLayout.childScaleHeight == true)
        {
            childComponentsJson += "\"childScaleHeight\":1,";
        }

        if (_horizontalLayout.childForceExpandWidth == true)
        {
            childComponentsJson += "\"childForceExpandWidth\":1,";
        }

        if (_horizontalLayout.childForceExpandHeight == true)
        {
            childComponentsJson += "\"childForceExpandHeight\":1,";
        }

        if (_horizontalLayout.childAlignment == TextAnchor.LowerCenter)
        {
            childComponentsJson += "\"childAlignment\":\"LowerCenter\",";
        }else if (_horizontalLayout.childAlignment == TextAnchor.LowerLeft)
        {
            childComponentsJson += "\"childAlignment\":\"LowerLeft\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.LowerRight)
        {
            childComponentsJson += "\"childAlignment\":\"LowerRight\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.MiddleCenter)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleCenter\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.MiddleLeft)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleLeft\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.MiddleRight)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleRight\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.UpperCenter)
        {
            childComponentsJson += "\"childAlignment\":\"UpperCenter\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.UpperLeft)
        {
            childComponentsJson += "\"childAlignment\":\"UpperLeft\",";
        }
        else if (_horizontalLayout.childAlignment == TextAnchor.UpperRight)
        {
            childComponentsJson += "\"childAlignment\":\"UpperRight\",";
        }



        childComponentsJson += "}";
        return childComponentsJson;
    }


    private string VerticalLayoutGroupToComponent(VerticalLayoutGroup _verticalLayout)
    {
        string childComponentsJson = "";
        childComponentsJson += "{\"type\":\"VerticalLayoutGroup\",";

        childComponentsJson += "\"top\":" + _verticalLayout.padding.top + ",";
        childComponentsJson += "\"left\":" + _verticalLayout.padding.left + ",";
        childComponentsJson += "\"right\":" + _verticalLayout.padding.right + ",";
        childComponentsJson += "\"bottom\":" + _verticalLayout.padding.bottom + ",";

        childComponentsJson += "\"spacing\":" + _verticalLayout.spacing + ",";

        if (_verticalLayout.reverseArrangement == true)
        {
            childComponentsJson += "\"reverseArrangement\":1,";
        }

        if (_verticalLayout.childControlWidth == true)
        {
            childComponentsJson += "\"childControlWidth\":1,";
        }

        if (_verticalLayout.childControlHeight == true)
        {
            childComponentsJson += "\"childControlHeight\":1,";
        }

        if (_verticalLayout.childScaleWidth == true)
        {
            childComponentsJson += "\"childScaleWidth\":1,";
        }

        if (_verticalLayout.childScaleHeight == true)
        {
            childComponentsJson += "\"childScaleHeight\":1,";
        }

        if (_verticalLayout.childForceExpandWidth == true)
        {
            childComponentsJson += "\"childForceExpandWidth\":1,";
        }

        if (_verticalLayout.childForceExpandHeight == true)
        {
            childComponentsJson += "\"childForceExpandHeight\":1,";
        }

        if (_verticalLayout.childAlignment == TextAnchor.LowerCenter)
        {
            childComponentsJson += "\"childAlignment\":\"LowerCenter\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.LowerLeft)
        {
            childComponentsJson += "\"childAlignment\":\"LowerLeft\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.LowerRight)
        {
            childComponentsJson += "\"childAlignment\":\"LowerRight\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.MiddleCenter)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleCenter\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.MiddleLeft)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleLeft\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.MiddleRight)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleRight\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.UpperCenter)
        {
            childComponentsJson += "\"childAlignment\":\"UpperCenter\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.UpperLeft)
        {
            childComponentsJson += "\"childAlignment\":\"UpperLeft\",";
        }
        else if (_verticalLayout.childAlignment == TextAnchor.UpperRight)
        {
            childComponentsJson += "\"childAlignment\":\"UpperRight\",";
        }



        childComponentsJson += "}";
        return childComponentsJson;
    }


    private string GridLayoutGroupToComponent(GridLayoutGroup _gridLayoutGroup)
    {
        string childComponentsJson = "";
        childComponentsJson += "{\"type\":\"GridLayoutGroup\",";

        childComponentsJson += "\"top\":" + _gridLayoutGroup.padding.top + ",";
        childComponentsJson += "\"left\":" + _gridLayoutGroup.padding.left + ",";
        childComponentsJson += "\"right\":" + _gridLayoutGroup.padding.right + ",";
        childComponentsJson += "\"bottom\":" + _gridLayoutGroup.padding.bottom + ",";

        childComponentsJson += "\"spacing\":{\"x\":" + _gridLayoutGroup.spacing.x + ",\"y\":" + _gridLayoutGroup.spacing.y + "},";

        childComponentsJson += "\"cellSize\":{\"x\":" + _gridLayoutGroup.cellSize.x + ",\"y\":" + _gridLayoutGroup.cellSize.y + "},";



        if (_gridLayoutGroup.startCorner == GridLayoutGroup.Corner.UpperLeft)
        {
            childComponentsJson += "\"startCorner\":\"UpperLeft\",";
        }else if (_gridLayoutGroup.startCorner == GridLayoutGroup.Corner.UpperRight)
        {
            childComponentsJson += "\"startCorner\":\"UpperRight\",";
        }
        else if (_gridLayoutGroup.startCorner == GridLayoutGroup.Corner.LowerLeft)
        {
            childComponentsJson += "\"startCorner\":\"LowerLeft\",";
        }
        else if (_gridLayoutGroup.startCorner == GridLayoutGroup.Corner.LowerRight)
        {
            childComponentsJson += "\"startCorner\":\"LowerRight\",";
        }

        if (_gridLayoutGroup.startAxis == GridLayoutGroup.Axis.Horizontal)
        {
            childComponentsJson += "\"startAxis\":\"Horizontal\",";
        }else if (_gridLayoutGroup.startAxis == GridLayoutGroup.Axis.Vertical)
        {
            childComponentsJson += "\"startAxis\":\"Vertical\",";
        }

        if (_gridLayoutGroup.constraint == GridLayoutGroup.Constraint.Flexible)
        {
            childComponentsJson += "\"constraint\":\"Flexible\",";
        }else if (_gridLayoutGroup.constraint == GridLayoutGroup.Constraint.FixedColumnCount)
        {
            childComponentsJson += "\"constraint\":\"FixedColumnCount\",";
            childComponentsJson += "\"constraintCount\":" + _gridLayoutGroup.constraintCount + ",";
        }
        else if (_gridLayoutGroup.constraint == GridLayoutGroup.Constraint.FixedRowCount)
        {
            childComponentsJson += "\"constraint\":\"FixedRowCount\",";
            childComponentsJson += "\"constraintCount\":" + _gridLayoutGroup.constraintCount + ",";
        }


        if (_gridLayoutGroup.childAlignment == TextAnchor.LowerCenter)
        {
            childComponentsJson += "\"childAlignment\":\"LowerCenter\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.LowerLeft)
        {
            childComponentsJson += "\"childAlignment\":\"LowerLeft\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.LowerRight)
        {
            childComponentsJson += "\"childAlignment\":\"LowerRight\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.MiddleCenter)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleCenter\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.MiddleLeft)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleLeft\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.MiddleRight)
        {
            childComponentsJson += "\"childAlignment\":\"MiddleRight\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.UpperCenter)
        {
            childComponentsJson += "\"childAlignment\":\"UpperCenter\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.UpperLeft)
        {
            childComponentsJson += "\"childAlignment\":\"UpperLeft\",";
        }
        else if (_gridLayoutGroup.childAlignment == TextAnchor.UpperRight)
        {
            childComponentsJson += "\"childAlignment\":\"UpperRight\",";
        }



        childComponentsJson += "}";
        return childComponentsJson;
    }

    public string getComponents(Transform child)
    {
        bool customComponent = false;

        Vector3 position = child.localPosition;
        Vector3 scale = child.localScale;
        Vector3 rotation = new Vector3(child.localEulerAngles.x, child.localEulerAngles.y, child.localEulerAngles.z);

        //Debug.Log(rotation);

        string childComponentsJson = "[";


        Image _Image = child.GetComponent<Image>();
        if (_Image != null)
        {

            childComponentsJson += ImageToComponent(_Image) + ",";

        }



        TextMeshProUGUI _TextMeshPro = child.GetComponent<TextMeshProUGUI>();

        if (_TextMeshPro != null)
        {
            childComponentsJson += TextMeshProUGUIToComponent(_TextMeshPro) + ",";
        }

        CustomInputField _customInputField = child.GetComponent<CustomInputField>();

        if (_customInputField != null)
        {
            customComponent = true;
            string customInputFieldJSON = "";

            customInputFieldJSON += "{\"type\":\"CustomInputField\",";

            customInputFieldJSON += "\"Image\":" + ImageToComponent(_customInputField.image) + ",";

            customInputFieldJSON += "\"Placeholder\":" + TextMeshProUGUIToComponent(_customInputField.placeholder) + ",";

            customInputFieldJSON += "\"Text\":" + TextMeshProUGUIToComponent(_customInputField.text) + ",";


            customInputFieldJSON += "},";

            childComponentsJson += customInputFieldJSON;

        }

        CustomSlider _customSlider = child.GetComponent<CustomSlider>();

        if (_customSlider != null)
        {
            customComponent = true;
            string customInputFieldJSON = "";

            customInputFieldJSON += "{\"type\":\"CustomSlider\",";

            customInputFieldJSON += "\"Background_Image\":" + ImageToComponent(_customSlider.BackgroundImage) + ",";
            customInputFieldJSON += "\"Background_RectTransform\":" + RectTransformToComponent(_customSlider.BackgroundRectTransform) + ",";

            customInputFieldJSON += "\"FillArea_RectTransform\":" + RectTransformToComponent(_customSlider.FillArea) + ",";

            customInputFieldJSON += "\"Fill_Image\":" + ImageToComponent(_customSlider.FillImage) + ",";
            customInputFieldJSON += "\"Fill_RectTransform\":" + RectTransformToComponent(_customSlider.FillRectTransform) + ",";

            customInputFieldJSON += "\"HandleSlideArea_RectTransform\":" + RectTransformToComponent(_customSlider.HandleSlideArea) + ",";

            customInputFieldJSON += "\"Handle_Image\":" + ImageToComponent(_customSlider.HandleImage) + ",";
            customInputFieldJSON += "\"Handle_RectTransform\":" + RectTransformToComponent(_customSlider.HandleRectTransform) + ",";

            customInputFieldJSON += "\"minValue\":" + _customSlider.slider.minValue + ",";
            customInputFieldJSON += "\"maxValue\":" + _customSlider.slider.maxValue + ",";

            if (_customSlider.slider.wholeNumbers == true)
            {
                customInputFieldJSON += "\"wholeNumbers\":1,";
            }

            customInputFieldJSON += "\"value\":" + _customSlider.slider.value + ",";

            if (_customSlider.slider.direction == Slider.Direction.LeftToRight)
            {
                customInputFieldJSON += "\"direction\":\"leftToRight\",";
            }
            else if (_customSlider.slider.direction == Slider.Direction.RightToLeft)
            {
                customInputFieldJSON += "\"direction\":\"rightToLeft\",";
            }
            else if (_customSlider.slider.direction == Slider.Direction.TopToBottom)
            {
                customInputFieldJSON += "\"direction\":\"topToBottom\",";
            }
            else if (_customSlider.slider.direction == Slider.Direction.BottomToTop)
            {
                customInputFieldJSON += "\"direction\":\"bottomToTop\",";
            }




            customInputFieldJSON += "},";

            childComponentsJson += customInputFieldJSON;

        }

        CustomScrollView _customScrollView = child.GetComponent<CustomScrollView>();

        if (_customScrollView != null)
        {
            customComponent = true;
            string customInputFieldJSON = "";

            customInputFieldJSON += "{\"type\":\"CustomScrollView\",";


            if (_customScrollView.scrollRect.horizontal == true)
            {
                customInputFieldJSON += "\"horizontal\":1,";
            }

            if (_customScrollView.scrollRect.vertical == true)
            {
                customInputFieldJSON += "\"vertical\":1,";
            }

            if (_customScrollView.scrollRect.horizontalScrollbarVisibility == ScrollRect.ScrollbarVisibility.Permanent)
            {
                customInputFieldJSON += "\"horizontalScrollbarVisibility\":\"Permanent\",";
            }
            else if (_customScrollView.scrollRect.horizontalScrollbarVisibility == ScrollRect.ScrollbarVisibility.AutoHide)
            {
                customInputFieldJSON += "\"horizontalScrollbarVisibility\":\"AutoHide\",";
            }
            else if (_customScrollView.scrollRect.horizontalScrollbarVisibility == ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport)
            {
                customInputFieldJSON += "\"horizontalScrollbarVisibility\":\"AutoHideAndExpandViewport\",";
                customInputFieldJSON += "\"horizontalScrollbarSpacing\":" + _customScrollView.scrollRect.horizontalScrollbarSpacing + ",";
            }

            if (_customScrollView.scrollRect.verticalScrollbarVisibility == ScrollRect.ScrollbarVisibility.Permanent)
            {
                customInputFieldJSON += "\"verticalScrollbarVisibility\":\"Permanent\",";
            }
            else if (_customScrollView.scrollRect.verticalScrollbarVisibility == ScrollRect.ScrollbarVisibility.AutoHide)
            {
                customInputFieldJSON += "\"verticalScrollbarVisibility\":\"AutoHide\",";
            }
            else if (_customScrollView.scrollRect.verticalScrollbarVisibility == ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport)
            {
                customInputFieldJSON += "\"verticalScrollbarVisibility\":\"AutoHideAndExpandViewport\",";
                customInputFieldJSON += "\"verticalScrollbarSpacing\":" + _customScrollView.scrollRect.verticalScrollbarSpacing + ",";
            }


            customInputFieldJSON += "\"content\":"+ getComponents(_customScrollView.content.transform) + ",";
            customInputFieldJSON += "\"contentName\":\"" + _customScrollView.content.gameObject.name + "\",";

            cacheGameObjectName(_customScrollView.content.gameObject);

            string childrenListJson = TraverseAllChildren(_customScrollView.content.transform);

            if (childrenListJson != "[]")
            {
                customInputFieldJSON += "\"children\":" + childrenListJson + ",";
            }


            /*customInputFieldJSON += "\"contentRectTransform\":" + RectTransformToComponent(_customScrollView.content.GetComponent<RectTransform>()) + ",";

            Image _contentImage = _customScrollView.content.GetComponent<Image>();

            if (_contentImage != null)
            {
                customInputFieldJSON += "\"contentImage\":" + ImageToComponent(_contentImage) + ",";
            }

            ContentSizeFitter _contentSizeFitter2 = _customScrollView.content.GetComponent<ContentSizeFitter>();

            if (_contentSizeFitter2 != null)
            {
                customInputFieldJSON += "\"contentSizeFitter\":" + ContentSizeFitterToComponent(_contentSizeFitter2) + ",";
            }

            HorizontalLayoutGroup _HorizontalLayoutGroup2 = _customScrollView.content.GetComponent<HorizontalLayoutGroup>();

            if (_HorizontalLayoutGroup2 != null)
            {
                customInputFieldJSON += "\"HorizontalLayoutGroup\":" + HorizontalLayoutGroupToComponent(_HorizontalLayoutGroup2) + ",";
            }

            VerticalLayoutGroup _VerticalLayoutGroup2 = _customScrollView.content.GetComponent<VerticalLayoutGroup>();

            if (_VerticalLayoutGroup2 != null)
            {
                customInputFieldJSON += "\"VerticalLayoutGroup\":" + VerticalLayoutGroupToComponent(_VerticalLayoutGroup2) + ",";
            }

            GridLayoutGroup _GridLayoutGroup2 = _customScrollView.content.GetComponent<GridLayoutGroup>();

            if (_GridLayoutGroup2 != null)
            {
                customInputFieldJSON += "\"GridLayoutGroup\":" + GridLayoutGroupToComponent(_GridLayoutGroup2) + ",";
            }
            */

            //GridLayoutGroupToComponent


            customInputFieldJSON += "\"scrollViewImage\":" + ImageToComponent(_customScrollView.scrollViewImage) + ",";

            customInputFieldJSON += "\"scrollBarHorizontal\":" + RectTransformToComponent(_customScrollView.scrollBarHorizontal) + ",";
            customInputFieldJSON += "\"scrollBarHorizontalImage\":" + ImageToComponent(_customScrollView.scrollBarHorizontalImage) + ",";

            customInputFieldJSON += "\"scrollBarHorizontalSlidingArea\":" + RectTransformToComponent(_customScrollView.scrollBarHorizontalSlidingArea) + ",";
            customInputFieldJSON += "\"scrollBarHorizontalHandle\":" + RectTransformToComponent(_customScrollView.scrollBarHorizontalHandle) + ",";
            customInputFieldJSON += "\"scrollBarHorizontalHandleImage\":" + ImageToComponent(_customScrollView.scrollBarHorizontalHandleImage) + ",";

            customInputFieldJSON += "\"scrollBarVertical\":" + RectTransformToComponent(_customScrollView.scrollBarVertical) + ",";
            customInputFieldJSON += "\"scrollBarVerticalImage\":" + ImageToComponent(_customScrollView.scrollBarVerticalImage) + ",";

            customInputFieldJSON += "\"scrollBarVerticalSlidingArea\":" + RectTransformToComponent(_customScrollView.scrollBarVerticalSlidingArea) + ",";
            customInputFieldJSON += "\"scrollBarVerticalHandle\":" + RectTransformToComponent(_customScrollView.scrollBarVerticalHandle) + ",";
            customInputFieldJSON += "\"scrollBarVerticalHandleImage\":" + ImageToComponent(_customScrollView.scrollBarVerticalHandleImage) + ",";

            customInputFieldJSON += "},";

            childComponentsJson += customInputFieldJSON;

        }

        GridLayoutGroup _GridLayoutGroup = child.GetComponent<GridLayoutGroup>();

        if (_GridLayoutGroup != null)
        {
            childComponentsJson += GridLayoutGroupToComponent(_GridLayoutGroup) + ",";
        }

        HorizontalLayoutGroup _HorizontalLayoutGroup = child.GetComponent<HorizontalLayoutGroup>();

        if (_HorizontalLayoutGroup != null)
        {
            childComponentsJson += HorizontalLayoutGroupToComponent(_HorizontalLayoutGroup) + ",";
        }

        VerticalLayoutGroup _VerticalLayoutGroup = child.GetComponent<VerticalLayoutGroup>();

        if (_VerticalLayoutGroup != null)
        {
            childComponentsJson += VerticalLayoutGroupToComponent(_VerticalLayoutGroup) + ",";
        }

        ContentSizeFitter _contentSizeFitter = child.GetComponent<ContentSizeFitter>();

        if (_contentSizeFitter != null)
        {
            childComponentsJson += ContentSizeFitterToComponent(_contentSizeFitter) + ",";
        }

        Button _Button = child.GetComponent<Button>();

        if (_Button != null)
        {
            childComponentsJson += "{\"type\":\"Button\",";


            childComponentsJson += "},";
        }


        RectTransform _RectTransform = child.GetComponent<RectTransform>();

        if (_RectTransform != null)
        {
            childComponentsJson += RectTransformToComponent(_RectTransform) + ",";
        }

        childComponentsJson += "]";

        int activeSelf = 1;
        if (child.gameObject.activeSelf == false)
        {
            activeSelf = 0;
        }

        string childJson = "{";
        //childJson += "\"position\":[" + position.x + "," + position.y + "," + position.z + "],";
        if (scale.x != 1f || scale.y != 1f || scale.z != 1f)
        {
            childJson += "\"scale\":[" + scale.x + "," + scale.y + "," + scale.z + "],";
        }
        if (rotation.x != 0f || rotation.y != 0f || rotation.z != 0f)
        {
            childJson += "\"rotation\":[" + rotation.x + "," + rotation.y + "," + rotation.z + "],";
        }
        if (activeSelf == 0)
        {
            childJson += "\"active\":" + activeSelf + ",";
        }

        childJson += "\"name\":\"" + child.gameObject.name + "\",";


        //childJson += "\"id\":" + currentPrefabID + ",";

        if (childComponentsJson != "[]")
        {
            childJson += "\"components\":" + childComponentsJson + ",";
        }


        // Call the function recursively to traverse its children

        //currentPrefabID += 1;

        //now going deeper
        if (customComponent == false)
        {
            string childrenListJson = TraverseAllChildren(child);

            if (childrenListJson != "[]")
            {
                childJson += "\"children\":" + childrenListJson + ",";
            }
        }



        childJson += "}";

        return childJson;
    }

    // Recursively traverse all children, including nested children
    public string TraverseAllChildren(Transform parent)
    {
        // Loop through each child of the current parent

        string list = "[";

        foreach (Transform child in parent)
        {
            // Do something with the child, for example, log its name
            //Debug.Log("Found child: " + child.name);

            cacheGameObjectName(child.gameObject);

            list += getComponents(child) + ",";

        }

        list += "]";

        return list;
    }


    public string ConvertSpriteToBase64(Sprite sprite)
    {
        if (sprite == null) return null;

        // Get the texture from the sprite
        Texture2D texture = sprite.texture;

        // Create a readable Texture2D in a compatible format (RGBA32)
        Texture2D readableTexture = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, TextureFormat.RGBA32, false);

        // Copy the pixels from the original texture to the new readable texture
        Color[] pixels = texture.GetPixels((int)sprite.rect.x, (int)sprite.rect.y, (int)sprite.rect.width, (int)sprite.rect.height);
        readableTexture.SetPixels(pixels);
        readableTexture.Apply();

        // Convert the texture to PNG format (or JPG if preferred)
        byte[] imageData = readableTexture.EncodeToPNG(); // Or EncodeToJPG for JPG format

        // Convert byte array to base64 string
        string base64String = System.Convert.ToBase64String(imageData);

        return base64String;
    }

}
