using UnityEngine;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;

// TODO: Move to same document as WildsEditorWindow
// Core editor interface for holding folder and stylesheet information
public interface IWildsEditor{
    public string layoutsFolder{ get; }
    public string stylesheetsFolder{ get; }
}

// TODO: Move to own document
// Core editor window for all classes in document
public abstract class WildsEditorWindow : Editor, IWildsEditor{
    public abstract string layoutsFolder { get; }
    public abstract string stylesheetsFolder { get; }
        
    string coreLayoutsFolder = "Assets/Core/UI/Editor/Layouts/";
    //string coreStylesheetsFolder = "Assets/Core/UI/Editor/Stylesheets/";
        
    public override VisualElement CreateInspectorGUI(){
        VisualElement newEditorWindow = GetVisualElement();

        VisualElement inspectorFoldout = AssetDatabase
            .LoadAssetAtPath<VisualTreeAsset>(coreLayoutsFolder + "/Common/DefaultInspectorFoldout.uxml").Instantiate();
        
        newEditorWindow.Add(inspectorFoldout);
        
        AddOriginalInspector(inspectorFoldout);
        
        return newEditorWindow;
    }

    public VisualElement GetVisualElement(){
        VisualElement myInspector = null;

        string GetVisualTreeString(){
            return coreLayoutsFolder + layoutsFolder + "/" + this.GetType().FullName + ".uxml";
        }
        
        try {
            myInspector = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(GetVisualTreeString()).Instantiate();
        } catch {
            Debug.LogError($"Failed to find the following layout: {GetVisualTreeString()}");
        }

        BindEditor(myInspector);
        
        return myInspector;
    }

    public abstract void BindEditor(VisualElement element);

    public void AddOriginalInspector(VisualElement foldout){
        // Attach a default Inspector to the Foldout.
        InspectorElement.FillDefaultInspector(foldout.Q("DefaultFoldout"), serializedObject, this);
    }
    
}

// Core editor window for all player classes in document. Mainly just so if I change the player folder I don't have to change every classes layoutsFolder, just this one. (or whatever class)
public abstract class PlayerEditorWindow : WildsEditorWindow{
    public override string layoutsFolder{ get; } = "Player";
    public override string stylesheetsFolder{ get; } = "";
}

[CustomEditor(typeof(PlayerControls))]
public class PlayerControlsInspector: PlayerEditorWindow{
    public PlayerControls script;
    public Object player;

    public override void BindEditor(VisualElement element){
        SerializedObject so = new (player);
        element.dataSource = player;
    }

    void OnEnable(){
        player = target;
    }
}
