// Warning: Some assembly references could not be resolved automatically. This might lead to incorrect decompilation of some parts,
// for ex. property getter/setter access. To get optimal decompilation results, please manually add the missing references to the list of loaded assemblies.
// EdenAutoMorpherEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// Eden.AutoMorpher.EdenAutoMorpherEditor
using Eden.AutoMorpher;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(EdenAutoMorpher))]
public class EdenAutoMorpherEditor : Editor
{
    private const string _version = "2.2.2";

    private const string documentationUrl = "https://0xseoul.notion.site/How-to-Use-2bd1bca8582e8054a642efa8b35f4a9d";

    private const string questionUrl = "https://0xseoul.notion.site/Q-A-2bd1bca8582e80bc8122cb0cace28d25?source=copy_link";

    private const string discordUrl = "https://discord.gg/DgquvzGHC8";

    private MorpherMode _currentMode;

    private ResultInfo _resultInfo = new ResultInfo();

    private Stopwatch _stopwatch = new Stopwatch();

    private bool _showStepByStepProgress;

    private bool _showAdvanced;

    private bool _showMeshDetails;

    private List<string> _profileNames = new List<string>();

    private int _profileIndex;

    private Vector2 _errorMessageScroll = Vector2.zero;

    private const string PREF_KEY_MODE = "EdenAutoMorpher_Mode";

    private const string PREF_KEY_Profile = "EdenAutoMorpher_LastProfile";

    private IEnumerator _morphingEnumerator;

    private EdenAutoMorpher _edenAutoMorpher;

    private string _selectedProfileName = "";

    private bool _isProgressing;

    private bool _isUpdateWorking;

    private AutoMorpherValidator _validator;

    private AutoMorpherLogCollector _logCollector;

    private SerializedProperty _sourceAvatarObject;

    private SerializedProperty _sourceClothesObject;

    private SerializedProperty _sourceBodyMeshes;

    private SerializedProperty _profileName;

    private SerializedProperty _targetAvatarObject;

    private SerializedProperty _targetClothesObjectOriginal;

    private SerializedProperty _targetBodyMeshes;

    private SerializedProperty _minMargin;

    private SerializedProperty _worldRadius;

    private SerializedProperty _sigma;

    private SerializedProperty _smoothingIteration;

    private SerializedProperty _fittingExpandIteration;

    private SerializedProperty _fittingShrinkIteration;

    private SerializedProperty _isBodyAutoSetup;

    private SerializedProperty _isReparentAccessoryBonesToTargetAvatar;

    private SerializedProperty _skipFootFitting;

    private SerializedProperty _transferWeightToAvatar;

    private SerializedProperty _addAnchorBone;

    private SerializedProperty _armatureBoneScaleCopy;

    private SerializedProperty _isRemoveAutoMorphedClothes;

    private void OnEnable()
    {
        this._validator = new AutoMorpherValidator();
        this._logCollector = new AutoMorpherLogCollector();
        this._currentMode = (MorpherMode)EditorPrefs.GetInt("EdenAutoMorpher_Mode", 0);
        this._selectedProfileName = EditorPrefs.GetString("EdenAutoMorpher_LastProfile", "");
        this._sourceAvatarObject = base.serializedObject.FindProperty("sourceAvatarObject");
        this._sourceClothesObject = base.serializedObject.FindProperty("sourceClothesObject");
        this._sourceBodyMeshes = base.serializedObject.FindProperty("sourceBodyMeshes");
        this._profileName = base.serializedObject.FindProperty("profileName");
        this._targetAvatarObject = base.serializedObject.FindProperty("targetAvatarObject");
        this._targetClothesObjectOriginal = base.serializedObject.FindProperty("targetClothesObjectOriginal");
        this._targetBodyMeshes = base.serializedObject.FindProperty("targetBodyMeshes");
        this._minMargin = base.serializedObject.FindProperty("minMargin");
        this._worldRadius = base.serializedObject.FindProperty("worldRadius");
        this._sigma = base.serializedObject.FindProperty("sigma");
        this._smoothingIteration = base.serializedObject.FindProperty("smoothingIteration");
        this._fittingExpandIteration = base.serializedObject.FindProperty("fittingExpandIteration");
        this._fittingShrinkIteration = base.serializedObject.FindProperty("fittingShrinkIteration");
        this._isBodyAutoSetup = base.serializedObject.FindProperty("isBodyAutoSetup");
        this._isReparentAccessoryBonesToTargetAvatar = base.serializedObject.FindProperty("isReparentAccessoryBonesToTargetAvatar");
        this._skipFootFitting = base.serializedObject.FindProperty("skipFootFitting");
        this._transferWeightToAvatar = base.serializedObject.FindProperty("transferWeightToAvatar");
        this._addAnchorBone = base.serializedObject.FindProperty("addAnchorBone");
        this._armatureBoneScaleCopy = base.serializedObject.FindProperty("armatureBoneScaleCopy");
        this._isRemoveAutoMorphedClothes = base.serializedObject.FindProperty("isRemoveAutoMorphedClothes");
        this.RefreshProfiles();
    }

    private void OnDestroy()
    {
        this.StopProcess();
    }

    public override void OnInspectorGUI()
    {
        //IL_002e: Unknown result type (might be due to invalid IL or missing references)
        //IL_0033: Unknown result type (might be due to invalid IL or missing references)
        //IL_0034: Unknown result type (might be due to invalid IL or missing references)
        //IL_0035: Unknown result type (might be due to invalid IL or missing references)
        //IL_0043: Unknown result type (might be due to invalid IL or missing references)
        //IL_0061: Unknown result type (might be due to invalid IL or missing references)
        //IL_0066: Unknown result type (might be due to invalid IL or missing references)
        //IL_0075: Unknown result type (might be due to invalid IL or missing references)
        //IL_0076: Unknown result type (might be due to invalid IL or missing references)
        //IL_0079: Unknown result type (might be due to invalid IL or missing references)
        EditorGUILayout.Space(4f);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("EDEN Auto Morpher", EditorStyles.boldLabel);
        GUILayout.FlexibleSpace();
        Language currentLanguage = LanguageManager.CurrentLanguage;
        Language val = currentLanguage;
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            val = (Language)(object)EditorGUILayout.EnumPopup((Enum)(object)currentLanguage, GUILayout.Width(80f));
        }
        if (val != currentLanguage)
        {
            LanguageManager.SetLanguage(val);
            GUI.FocusControl(null);
        }
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.LabelField("  - Version : 2.2.2", EditorStyles.boldLabel);
        EditorGUILayout.Space(6f);
        base.serializedObject.Update();
        this._edenAutoMorpher = (EdenAutoMorpher)base.target;
        this._isProgressing = this._morphingEnumerator != null;
        if (!this._isProgressing && this._isUpdateWorking)
        {
            this.StopProcess();
        }
        this.InfoBox();
        EditorGUILayout.Space();
        string text = LanguageManager.Get("UI.Mode.AutoFitting");
        string text2 = LanguageManager.Get("UI.Mode.ManualFitting");
        string text3 = LanguageManager.Get("UI.Mode.ProfileFitting");
        string[] texts = new string[3] { text, text2, text3 };
        int num = (int)this._currentMode;
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            num = GUILayout.Toolbar(num, texts);
        }
        if (num != (int)this._currentMode)
        {
            this._showAdvanced = false;
            this._showMeshDetails = false;
            this._currentMode = (MorpherMode)num;
            EditorPrefs.SetInt("EdenAutoMorpher_Mode", num);
            this._edenAutoMorpher.ChangeMode(this._currentMode);
        }
        switch (this._currentMode)
        {
            case MorpherMode.AutoMorpher:
                this.DrawAutoFittingMode(this._edenAutoMorpher, this._currentMode);
                break;
            case MorpherMode.ManualMorpher:
                this.DrawManualFittingMode(this._edenAutoMorpher, this._currentMode);
                break;
            case MorpherMode.ProfileMorpher:
                this.DrawProfileFittingMode(this._edenAutoMorpher, this._currentMode);
                break;
        }
        EditorGUILayout.Space();
        EditorGUILayout.Space();
        if (!this._isProgressing)
        {
            this.ApplyVariableConstraints();
            base.serializedObject.ApplyModifiedProperties();
        }
    }

    private void InfoBox()
    {
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        this.DrawLabelWithShortLink(" - How To Use:", "Open Documentation", "https://0xseoul.notion.site/How-to-Use-2bd1bca8582e8054a642efa8b35f4a9d");
        this.DrawLabelWithShortLink(" - Q&A:", "Open Q&A Page", "https://0xseoul.notion.site/Q-A-2bd1bca8582e80bc8122cb0cace28d25?source=copy_link");
        this.DrawLabelWithShortLink(" - Discord:", "Open Discord", "https://discord.gg/DgquvzGHC8");
        EditorGUILayout.EndVertical();
    }

    private void DrawLabelWithShortLink(string label, string linkText, string url)
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField(label, GUILayout.Width(90f));
        GUIStyle style = new GUIStyle(EditorStyles.linkLabel);
        Rect rect = GUILayoutUtility.GetRect(new GUIContent(linkText), style);
        EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
        if (GUI.Button(rect, linkText, style))
        {
            Application.OpenURL(url);
        }
        EditorGUILayout.EndHorizontal();
    }

    private void ApplyVariableConstraints()
    {
        if (this._minMargin != null)
        {
            this._minMargin.floatValue = Mathf.Max(0f, this._minMargin.floatValue);
        }
        if (this._sigma != null)
        {
            this._sigma.floatValue = Mathf.Max(0f, this._sigma.floatValue);
        }
        if (this._fittingExpandIteration != null)
        {
            this._fittingExpandIteration.intValue = Mathf.Max(0, this._fittingExpandIteration.intValue);
        }
        if (this._fittingShrinkIteration != null)
        {
            this._fittingShrinkIteration.intValue = Mathf.Max(0, this._fittingShrinkIteration.intValue);
        }
    }

    private void DrawAutoFittingMode(EdenAutoMorpher _edenAutoMorpher, MorpherMode morpherMode)
    {
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Basic Avatar Settings", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Source Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._sourceAvatarObject);
            EditorGUILayout.PropertyField(this._sourceClothesObject);
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Target Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._targetAvatarObject);
            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.Space();
            this.DrawBasicProperties(morpherMode);
            EditorGUILayout.Space();
            this.DrawAdvanceProperties();
            EditorGUILayout.Space();
        }
        EditorGUILayout.Space();
        Rect controlRect = EditorGUILayout.GetControlRect(false, 1f);
        controlRect.height = 3f;
        EditorGUI.DrawRect(controlRect, new Color(0f, 0f, 0f, 0.25f));
        EditorGUILayout.Space();
        GUIStyle gUIStyle = new GUIStyle(EditorStyles.boldLabel);
        gUIStyle.fontSize = 20;
        gUIStyle.wordWrap = true;
        EditorGUILayout.LabelField("Auto Morphing", gUIStyle);
        EditorGUILayout.Space();
        this.ShowInspectorProgress();
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            GUIStyle gUIStyle2 = new GUIStyle(GUI.skin.button);
            gUIStyle2.fontSize = 18;
            gUIStyle2.fixedHeight = 40f;
            gUIStyle2.alignment = TextAnchor.MiddleCenter;
            bool flag = true;
            GameObject sourceAvatar = this._sourceAvatarObject.objectReferenceValue as GameObject;
            GameObject sourceClothes = this._sourceClothesObject.objectReferenceValue as GameObject;
            GameObject targetAvatar = this._targetAvatarObject.objectReferenceValue as GameObject;
            flag = this._validator.ValidateAutoModeObjects(sourceAvatar, sourceClothes, targetAvatar, out var errorMessage);
            if (!flag)
            {
                EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
            }
            EditorGUILayout.Space();
            using (new EditorGUI.DisabledScope(!flag))
            {
                EditorGUILayout.Space();
                if (GUILayout.Button("Run All", gUIStyle2))
                {
                    this.StartAutoMorphing(_edenAutoMorpher, morpherMode);
                }
                EditorGUILayout.Space();
                EditorGUI.indentLevel++;
                this._showStepByStepProgress = EditorGUILayout.Foldout(this._showStepByStepProgress, "Step-by-step progress", toggleOnLabelClick: true);
                EditorGUI.indentLevel--;
                if (!this._showStepByStepProgress)
                {
                    return;
                }
                EditorGUILayout.Space();
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("1.Run Fitting", gUIStyle2))
                    {
                        this.StartFitting(_edenAutoMorpher, morpherMode);
                    }
                    bool flag2 = _edenAutoMorpher != null && _edenAutoMorpher.IsWeightingReady(isAutoMode: true);
                    using (new EditorGUI.DisabledScope(!flag2))
                    {
                        if (GUILayout.Button("2.Run Weighting", gUIStyle2))
                        {
                            this.StartWeighting(_edenAutoMorpher);
                        }
                    }
                }
            }
        }
    }

    private void DrawManualFittingMode(EdenAutoMorpher _edenAutoMorpher, MorpherMode morpherMode)
    {
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Basic Avatar Settings", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Source Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._sourceAvatarObject);
            EditorGUILayout.PropertyField(this._sourceClothesObject);
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Target Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._targetAvatarObject);
            EditorGUILayout.PropertyField(this._targetClothesObjectOriginal, new GUIContent("Target Clothes Object"));
            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.Space();
            this.DrawBasicProperties(morpherMode);
            EditorGUILayout.Space();
            this.DrawAdvanceProperties();
        }
        EditorGUILayout.Space();
        Rect controlRect = EditorGUILayout.GetControlRect(false, 1f);
        controlRect.height = 3f;
        EditorGUI.DrawRect(controlRect, new Color(0f, 0f, 0f, 0.25f));
        EditorGUILayout.Space();
        GUIStyle gUIStyle = new GUIStyle(EditorStyles.boldLabel);
        gUIStyle.fontSize = 20;
        gUIStyle.wordWrap = true;
        EditorGUILayout.LabelField("Auto Morphing", gUIStyle);
        EditorGUILayout.Space();
        this.ShowInspectorProgress();
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            GUIStyle gUIStyle2 = new GUIStyle(GUI.skin.button);
            gUIStyle2.fontSize = 18;
            gUIStyle2.fixedHeight = 40f;
            gUIStyle2.alignment = TextAnchor.MiddleCenter;
            bool flag = true;
            bool flag2 = true;
            GameObject sourceAvatar = this._sourceAvatarObject.objectReferenceValue as GameObject;
            GameObject sourceClothes = this._sourceClothesObject.objectReferenceValue as GameObject;
            GameObject targetAvatar = this._targetAvatarObject.objectReferenceValue as GameObject;
            GameObject targetClothes = this._targetClothesObjectOriginal.objectReferenceValue as GameObject;
            flag = this._validator.ValidateManualMode_AutoSetup_Objects(sourceAvatar, sourceClothes, targetAvatar, out var errorMessage);
            if (!flag)
            {
                EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
            }
            EditorGUILayout.Space();
            using (new EditorGUI.DisabledScope(!flag))
            {
                if (GUILayout.Button("0. Auto Setup", gUIStyle2))
                {
                    try
                    {
                        _edenAutoMorpher.AutoPoseSetup(morpherMode);
                        this._resultInfo.isComplicated = true;
                        this._resultInfo.processEndState = "Auto Setup Success";
                    }
                    catch (AutoMorpherException ex)
                    {
                        UnityEngine.Debug.LogException(ex);
                        string text = ex.title ?? "Eden AutoMorpher Error";
                        string text2 = ex.Message + "\n\nIf you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.";
                        EditorUtility.DisplayDialog(text, text2, "OK");
                        this._resultInfo.isComplicated = true;
                        this._resultInfo.processEndState = "Failed";
                        this._resultInfo.errorMessage = text + "\n\n" + text2;
                    }
                    catch (Exception ex2)
                    {
                        UnityEngine.Debug.LogException(ex2);
                        string text3 = "Unexpected Error";
                        string text4 = "If you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.\n\nError Details:\n" + ex2.ToString();
                        EditorUtility.DisplayDialog(text3, text4, "OK");
                        this._resultInfo.isComplicated = true;
                        this._resultInfo.processEndState = "Failed";
                        this._resultInfo.errorMessage = text3 + "\n\n" + text4;
                    }
                }
            }
            EditorGUILayout.Space();
            flag2 = this._validator.ValidateManualModeObjects(sourceAvatar, sourceClothes, targetAvatar, targetClothes, out errorMessage);
            if (!flag2)
            {
                EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
            }
            EditorGUILayout.Space();
            using (new EditorGUI.DisabledScope(!flag2))
            {
                if (GUILayout.Button("Run All", gUIStyle2))
                {
                    this.StartAutoMorphing(_edenAutoMorpher, morpherMode);
                }
                EditorGUILayout.Space();
                EditorGUI.indentLevel++;
                this._showStepByStepProgress = EditorGUILayout.Foldout(this._showStepByStepProgress, "Step-by-step progress", toggleOnLabelClick: true);
                EditorGUI.indentLevel--;
                if (!this._showStepByStepProgress)
                {
                    return;
                }
                EditorGUILayout.Space();
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("1. Run Fitting", gUIStyle2))
                    {
                        this.StartFitting(_edenAutoMorpher, morpherMode);
                    }
                    bool flag3 = flag2 && _edenAutoMorpher != null && _edenAutoMorpher.IsWeightingReady(isAutoMode: false);
                    using (new EditorGUI.DisabledScope(!flag3))
                    {
                        if (GUILayout.Button("2. Run Weighting", gUIStyle2))
                        {
                            this.StartWeighting(_edenAutoMorpher);
                        }
                    }
                }
            }
        }
    }

    private void DrawProfileFittingMode(EdenAutoMorpher _edenAutoMorpher, MorpherMode morpherMode)
    {
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Basic Avatar Settings", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Source Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            if (this._profileNames == null || this._profileNames.Count == 0)
            {
                this.RefreshProfiles();
            }
            using (new EditorGUILayout.HorizontalScope())
            {
                float labelWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = labelWidth - 14f;
                EditorGUILayout.PrefixLabel("Profile");
                base.serializedObject.Update();
                if (this._profileNames != null && this._profileNames.Count > 0)
                {
                    int num = EditorGUILayout.Popup(this._profileIndex, this._profileNames.ToArray());
                    if (num != this._profileIndex)
                    {
                        this._profileIndex = num;
                        this._selectedProfileName = this._profileNames[this._profileIndex];
                        EditorPrefs.SetString("EdenAutoMorpher_LastProfile", this._selectedProfileName);
                        if (this._profileName != null)
                        {
                            this._profileName.stringValue = this._selectedProfileName;
                        }
                    }
                }
                else
                {
                    EditorGUILayout.LabelField("No profiles found");
                }
                GUILayout.Space(8f);
                if (GUILayout.Button("Refresh", GUILayout.Width(70f)))
                {
                    this.RefreshProfiles();
                }
                EditorGUIUtility.labelWidth = labelWidth;
            }
            EditorGUILayout.PropertyField(this._sourceClothesObject);
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Target Avatar", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._targetAvatarObject);
            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.Space();
            this.DrawBasicProperties(morpherMode);
            EditorGUILayout.Space();
            this.DrawAdvanceProperties();
            EditorGUILayout.Space();
        }
        EditorGUILayout.Space();
        Rect controlRect = EditorGUILayout.GetControlRect(false, 1f);
        controlRect.height = 3f;
        EditorGUI.DrawRect(controlRect, new Color(0f, 0f, 0f, 0.25f));
        EditorGUILayout.Space();
        GUIStyle gUIStyle = new GUIStyle(EditorStyles.boldLabel);
        gUIStyle.fontSize = 20;
        gUIStyle.wordWrap = true;
        EditorGUILayout.LabelField("Auto Morphing", gUIStyle);
        EditorGUILayout.Space();
        this.ShowInspectorProgress();
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            GUIStyle gUIStyle2 = new GUIStyle(GUI.skin.button);
            gUIStyle2.fontSize = 18;
            gUIStyle2.fixedHeight = 40f;
            gUIStyle2.alignment = TextAnchor.MiddleCenter;
            if (AutoMorpherDev.isDeveloperMode)
            {
                using (new EditorGUI.DisabledScope(this._isProgressing))
                {
                    if (GUILayout.Button("0. Auto Setup", gUIStyle2))
                    {
                        try
                        {
                            _edenAutoMorpher.ProfileSetup(morpherMode);
                            this._resultInfo.isComplicated = true;
                            this._resultInfo.processEndState = "Auto Setup Success";
                        }
                        catch (AutoMorpherException ex)
                        {
                            UnityEngine.Debug.LogException(ex);
                            string text = ex.title ?? "Eden AutoMorpher Error";
                            string text2 = ex.Message + "\n\nIf you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.";
                            EditorUtility.DisplayDialog(text, text2, "OK");
                            this._resultInfo.isComplicated = true;
                            this._resultInfo.processEndState = "Failed";
                            this._resultInfo.errorMessage = text + "\n\n" + text2;
                        }
                        catch (Exception ex2)
                        {
                            UnityEngine.Debug.LogException(ex2);
                            string text3 = "Unexpected Error";
                            string text4 = "If you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.\n\nError Details:\n" + ex2.ToString();
                            EditorUtility.DisplayDialog(text3, text4, "OK");
                            this._resultInfo.isComplicated = true;
                            this._resultInfo.processEndState = "Failed";
                            this._resultInfo.errorMessage = text3 + "\n\n" + text4;
                        }
                    }
                }
            }
            GameObject sourceClothes = this._sourceClothesObject.objectReferenceValue as GameObject;
            GameObject targetAvatar = this._targetAvatarObject.objectReferenceValue as GameObject;
            string errorMessage;
            bool flag = this._validator.ValidateProfileModeObjects(sourceClothes, targetAvatar, out errorMessage);
            if (!flag)
            {
                EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
            }
            EditorGUILayout.Space();
            using (new EditorGUI.DisabledScope(!flag))
            {
                if (GUILayout.Button("Run All", gUIStyle2))
                {
                    this.StartAutoMorphing(_edenAutoMorpher, morpherMode);
                }
                EditorGUILayout.Space();
                EditorGUI.indentLevel++;
                this._showStepByStepProgress = EditorGUILayout.Foldout(this._showStepByStepProgress, "Step-by-step progress", toggleOnLabelClick: true);
                EditorGUI.indentLevel--;
                if (!this._showStepByStepProgress)
                {
                    return;
                }
                EditorGUILayout.Space();
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("1.Run Fitting", gUIStyle2))
                    {
                        this.StartFitting(_edenAutoMorpher, morpherMode);
                    }
                    bool flag2 = _edenAutoMorpher != null && _edenAutoMorpher.IsWeightingReady(isAutoMode: true);
                    using (new EditorGUI.DisabledScope(!flag2))
                    {
                        if (GUILayout.Button("2.Run Weighting", gUIStyle2))
                        {
                            this.StartWeighting(_edenAutoMorpher);
                        }
                    }
                }
            }
        }
    }

    private void RefreshProfiles()
    {
        ProfileLoader profileLoader = new ProfileLoader();
        this._profileNames = profileLoader.GetProfileList();
        if (this._profileNames == null || this._profileNames.Count == 0)
        {
            this._profileIndex = 0;
            this._selectedProfileName = "";
            if (this._profileName != null)
            {
                base.serializedObject.Update();
                this._profileName.stringValue = "";
                base.serializedObject.ApplyModifiedProperties();
            }
            return;
        }
        int num = this._profileNames.IndexOf(this._selectedProfileName);
        if (num >= 0)
        {
            this._profileIndex = num;
        }
        else
        {
            this._profileIndex = Mathf.Clamp(this._profileIndex, 0, this._profileNames.Count - 1);
        }
        this._selectedProfileName = this._profileNames[this._profileIndex];
        if (this._profileName != null)
        {
            base.serializedObject.Update();
            this._profileName.stringValue = this._selectedProfileName;
            base.serializedObject.ApplyModifiedProperties();
        }
    }

    private void ShowInspectorProgress()
    {
        if (this._isProgressing)
        {
            using (new EditorGUI.DisabledGroupScope(disabled: false))
            {
                ProcessInfo processInfo = this._edenAutoMorpher.GetProcessInfo();
                EditorGUILayout.HelpBox("ProgressInfo\n\n" + processInfo.title + "\n" + processInfo.text, MessageType.Info);
                EditorGUILayout.Space();
                EditorGUI.ProgressBar(GUILayoutUtility.GetRect(18f, 18f, "TextField"), processInfo.progress, $"{processInfo.progress * 100f:0}%");
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                if (GUILayout.Button("Stop"))
                {
                    this.StopProcess();
                    this._edenAutoMorpher.StopProcess();
                    this._resultInfo.processEndState = "Stopped";
                }
            }
        }
        else if (this._resultInfo.isComplicated)
        {
            EditorGUILayout.HelpBox(this._resultInfo.processTyep + " is " + this._resultInfo.processEndState + "\n  - Progressing time : " + this._resultInfo.processTime, MessageType.Info);
            if (this._resultInfo.processEndState == "Failed")
            {
                EditorGUILayout.Space(6f);
                using (new EditorGUILayout.VerticalScope(new GUIStyle(EditorStyles.helpBox)
                {
                    padding = new RectOffset(10, 10, 8, 8)
                }))
                {
                    GUIStyle style = new GUIStyle(EditorStyles.boldLabel)
                    {
                        normal =
                        {
                            textColor = Color.red
                        }
                    };
                    EditorGUILayout.LabelField("Error Occurred", style);
                    EditorGUILayout.Space(4f);
                    float height = 160f;
                    this._errorMessageScroll = EditorGUILayout.BeginScrollView(this._errorMessageScroll, GUILayout.Height(height));
                    EditorGUILayout.TextArea(this._resultInfo.errorMessage ?? string.Empty, GUILayout.ExpandHeight(expand: true));
                    EditorGUILayout.EndScrollView();
                }
            }
        }
        EditorGUILayout.Space();
    }

    private void DrawMeshProperties()
    {
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            this._showMeshDetails = EditorGUILayout.Foldout(this._showMeshDetails, "Mesh Info", toggleOnLabelClick: true);
        }
        if (this._showMeshDetails)
        {
            using (new EditorGUI.DisabledGroupScope(this._isProgressing))
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("Mesh Lists", EditorStyles.boldLabel);
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("Source Avatar Meshes", EditorStyles.boldLabel);
                EditorGUILayout.PropertyField(this._sourceBodyMeshes, new GUIContent("Source Body Meshes"), true);
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("Target Avatar Meshes", EditorStyles.boldLabel);
                EditorGUILayout.PropertyField(this._targetBodyMeshes, new GUIContent("Target Body Meshes"), true);
                EditorGUI.indentLevel--;
            }
        }
    }

    private void DrawBasicProperties(MorpherMode morpherMode)
    {
        EditorGUILayout.LabelField("Body Mesh", EditorStyles.boldLabel);
        using (new EditorGUI.DisabledScope(disabled: true))
        {
            GUIStyle gUIStyle = new GUIStyle(EditorStyles.miniLabel);
            gUIStyle.wordWrap = true;
            EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.BodyMeshInfo"), gUIStyle, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 40f));
        }
        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(this._isBodyAutoSetup, new GUIContent(LanguageManager.Get("UI.Property.BodyMeshTitle")), true);
        if (!this._edenAutoMorpher.isBodyAutoSetup)
        {
            if (morpherMode != MorpherMode.ProfileMorpher)
            {
                EditorGUILayout.LabelField("Source Avatar Meshes", EditorStyles.boldLabel);
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(this._sourceBodyMeshes, new GUIContent("Source Body Meshes"), true);
                EditorGUI.indentLevel--;
                EditorGUILayout.Space();
            }
            EditorGUILayout.LabelField("Target Avatar Meshes", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this._targetBodyMeshes, new GUIContent("Target Body Meshes"), true);
            EditorGUI.indentLevel--;
        }
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Min Margin", EditorStyles.boldLabel);
        using (new EditorGUI.DisabledScope(disabled: true))
        {
            GUIStyle gUIStyle2 = new GUIStyle(EditorStyles.miniLabel);
            gUIStyle2.wordWrap = true;
            EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.MinMarginInfo"), gUIStyle2, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 40f));
        }
        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(this._minMargin);
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Skip Foot Fitting", EditorStyles.boldLabel);
        using (new EditorGUI.DisabledScope(disabled: true))
        {
            GUIStyle style = new GUIStyle(EditorStyles.miniLabel)
            {
                wordWrap = true
            };
            EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.SkipFootFittingInfo"), style, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 40f));
        }
        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(this._skipFootFitting);
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Remove AutoMorphed Other Clothes", EditorStyles.boldLabel);
        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(this._isRemoveAutoMorphedClothes, new GUIContent("Remove AutoMorphed Other Clothes"));
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
    }

    private void DrawAdvanceProperties()
    {
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            this._showAdvanced = EditorGUILayout.Foldout(this._showAdvanced, "Advanced Option", toggleOnLabelClick: true);
        }
        if (!this._showAdvanced)
        {
            return;
        }
        using (new EditorGUI.DisabledGroupScope(this._isProgressing))
        {
            GUIStyle style = new GUIStyle(GUI.skin.box)
            {
                padding = new RectOffset(12, 12, 10, 12),
                margin = new RectOffset(0, 0, 8, 8)
            };
            GUIStyle style2 = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 13
            };
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("- Fitting Settings", style2);
            using (new EditorGUILayout.VerticalScope(style))
            {
                using (new EditorGUI.DisabledScope(disabled: true))
                {
                    EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.SigmaInfo"), EditorStyles.miniLabel);
                }
                EditorGUILayout.PropertyField(this._sigma);
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                using (new EditorGUI.DisabledScope(disabled: true))
                {
                    GUIStyle style3 = new GUIStyle(EditorStyles.miniLabel)
                    {
                        wordWrap = true
                    };
                    EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.SmoothingInfo"), style3);
                }
                EditorGUILayout.PropertyField(this._smoothingIteration);
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("Fitting Iterations", EditorStyles.boldLabel);
                using (new EditorGUI.DisabledScope(disabled: true))
                {
                    EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.IterationInfo"), EditorStyles.miniLabel);
                }
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(this._fittingExpandIteration, new GUIContent("Expand Iteration"));
                EditorGUILayout.PropertyField(this._fittingShrinkIteration, new GUIContent("Shrink Iteration"));
                EditorGUI.indentLevel--;
            }
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("- Weighting Settings", style2);
            using (new EditorGUILayout.VerticalScope(style))
            {
                EditorGUILayout.PropertyField(this._transferWeightToAvatar, new GUIContent("Transfer Weight To Avatar"));
                bool boolValue = this._transferWeightToAvatar.boolValue;
                if (boolValue)
                {
                    using (new EditorGUI.DisabledScope(!boolValue))
                    {
                        using (new EditorGUI.DisabledScope(disabled: true))
                        {
                            EditorGUILayout.LabelField(LanguageManager.Get("UI.Property.ReparentAccessoryBones"), EditorStyles.miniLabel);
                        }
                        EditorGUI.indentLevel++;
                        EditorGUILayout.PropertyField(this._isReparentAccessoryBonesToTargetAvatar, new GUIContent("Reparent Accessory Bones"));
                        EditorGUI.indentLevel--;
                    }
                }
                else
                {
                    if (this._isReparentAccessoryBonesToTargetAvatar.boolValue)
                    {
                        this._isReparentAccessoryBonesToTargetAvatar.boolValue = false;
                    }
                    EditorGUILayout.Space();
                    EditorGUI.indentLevel++;
                    EditorGUILayout.LabelField("Adds an anchor bone to preserve clothes bone rotation.", EditorStyles.boldLabel);
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(this._addAnchorBone, new GUIContent("Add Anchor Bone"));
                    EditorGUI.indentLevel--;
                    EditorGUI.indentLevel--;
                }
            }
            EditorGUI.indentLevel--;
        }
    }

    private void StartAutoMorphing(EdenAutoMorpher _edenAutoMorpher, MorpherMode _modeIndex)
    {
        this.StartProcess(_edenAutoMorpher, _edenAutoMorpher.AutoMorphingEnumerator(_modeIndex), "Auto Morphing");
    }

    private void StartFitting(EdenAutoMorpher _edenAutoMorpher, MorpherMode morpherMode)
    {
        this.StartProcess(_edenAutoMorpher, _edenAutoMorpher.FittingEnumerator(morpherMode), "Fitting");
    }

    private void StartWeighting(EdenAutoMorpher _edenAutoMorpher)
    {
        this.StartProcess(_edenAutoMorpher, _edenAutoMorpher.WeightingEnumerator(), "Weighting");
    }

    private void StartProcess(EdenAutoMorpher _edenAutoMorpher, IEnumerator enumerator, string processType)
    {
        if (this._morphingEnumerator != null)
        {
            UnityEngine.Debug.LogWarning("[EdenAutoMorpherEditor] Already AutoMorpher is Working");
            return;
        }
        this._edenAutoMorpher = _edenAutoMorpher;
        this._morphingEnumerator = enumerator;
        this._resultInfo.processTyep = processType;
        this._resultInfo.processTime = string.Empty;
        this._resultInfo.processEndState = "Unknown";
        this._resultInfo.isComplicated = false;
        this._stopwatch.Reset();
        this._stopwatch.Start();
        this._logCollector.BeginCapture();
        EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.OnEditorUpdate));
        EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.OnEditorUpdate));
        UnityEngine.Debug.Log("[EdenAutoMorpherEditor] Start " + processType + " Process");
    }

    private void StopProcess()
    {
        if (this._isUpdateWorking)
        {
            EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.OnEditorUpdate));
            if (this._stopwatch.IsRunning)
            {
                this._stopwatch.Stop();
                double totalSeconds = this._stopwatch.Elapsed.TotalSeconds;
                this._resultInfo.processTime = $"{totalSeconds:F2} sec";
                this._resultInfo.isComplicated = true;
            }
            EditorUtility.ClearProgressBar();
            SceneView.RepaintAll();
            EditorApplication.QueuePlayerLoopUpdate();
            InternalEditorUtility.RepaintAllViews();
            this._logCollector.SaveToTextFile("EdenAutoMorpher_Report.txt", includeWarningsAndInfo: true);
            this._logCollector.EndCapture();
            this._morphingEnumerator = null;
            this._isProgressing = false;
            this._isUpdateWorking = false;
            UnityEngine.Debug.Log("[EdenAutoMorpherEditor] AutoMorphing Process Ended");
        }
    }

    private void OnEditorUpdate()
    {
        if (this._morphingEnumerator == null || this._edenAutoMorpher == null)
        {
            this.StopProcess();
            return;
        }
        this._isUpdateWorking = true;
        try
        {
            bool flag = this._morphingEnumerator.MoveNext();
            ProcessInfo processInfo = this._edenAutoMorpher.GetProcessInfo();
            try
            {
                processInfo = this._edenAutoMorpher.GetProcessInfo();
            }
            catch
            {
                processInfo.title = "Eden AutoMorpher";
                processInfo.text = "Processing...";
                processInfo.progress = 0f;
            }
            if (EditorUtility.DisplayCancelableProgressBar(processInfo.title, processInfo.text, processInfo.progress))
            {
                UnityEngine.Debug.Log("[EdenAutoMorpherEditor] User Canceled Process");
                this._edenAutoMorpher.StopProcess();
                this.StopProcess();
                this._resultInfo.processEndState = "Stopped";
            }
            else if (!flag)
            {
                this.StopProcess();
                this._resultInfo.processEndState = "Ended";
            }
            else
            {
                this.Repaint();
            }
        }
        catch (AutoMorpherException ex)
        {
            EditorUtility.ClearProgressBar();
            UnityEngine.Debug.LogException(ex);
            this.StopProcess();
            string text = ex.title ?? "Eden AutoMorpher Error";
            string text2 = ex.Message + "\n\nIf you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.";
            EditorUtility.DisplayDialog(text, text2, "OK");
            this._resultInfo.processEndState = "Failed";
            this._resultInfo.errorMessage = text + "\n\n" + text2;
        }
        catch (Exception ex2)
        {
            EditorUtility.ClearProgressBar();
            UnityEngine.Debug.LogException(ex2);
            this.StopProcess();
            string text3 = "Unexpected Error";
            string text4 = "If you need assistance resolving this issue,\nplease contact us on Discord and include the following information:\n\n1. A screenshot of the Console window showing the error message.\n2. A screenshot of the current Hierarchy window.\n3. This error dialog, including the avatar and clothing information used.\n4. The log file saved at:\n   Assets/@Eden_Tools/Eden_AutoMorpher/Logs/EdenAutoMorpher_Report.txt\n\nProviding these details will help us identify the issue more accurately.\n\nError Details:\n" + ex2.ToString();
            EditorUtility.DisplayDialog(text3, text4, "OK");
            this._resultInfo.processEndState = "Failed";
            this._resultInfo.errorMessage = text3 + "\n\n" + text4;
        }
    }
}
