using UnityEngine;
using System.Collections.Generic;

public class Model
{
    public string nameHuman { get; internal set; } // human-readable name
    public string nameId { get; internal set; } // JSON export name, should be unique
    public Mesh mesh { get; internal set; } // obj/fbx
    public Material material { get; internal set; } // skin


    public readonly List<Port> ports;

    public Model(string nameHuman, string nameId, Mesh mesh, Material material, List<Port> ports = null)
    {
        this.nameHuman = nameHuman;
        this.nameId = nameId;
        this.mesh = mesh;
        this.material = material;
        this.ports = ports;
    }

    public bool hasPorts()
    {
        return ports != null && ports.Count > 0;
    }

    public void addPort(Port port)
    {
        ports.Add(port);
    }

    /// <summary>
    /// Spawns all Port-GO's, should be called only once
    /// </summary>
    /// <param name="parent"><c>gameObject</c> in the MonoBehaviour</param>
    /// <returns>All spawned GO's</returns>
    public List<GameObject> spawnAllPorts(GameObject parent)
    {
        Debug.Log($"{this.nameId}: Spawning {parent.name} count of {ports.Count} Ports");
        List<GameObject> ret = new List<GameObject>();
        for (int i = 0; i < ports.Count; i++)
        {
            var port = ports[i];
            Debug.Log(i + ". Creating port " + port.port);
            // bike:wheel:num
            GameObject child = new GameObject(parent.name + ":" + port.port + ":" + i);
            ChildModelBehaviour cmb = child.AddComponent<ChildModelBehaviour>();

            var mm = Object.FindAnyObjectByType<ModelManager>();
            if (mm == null)
            {
                Debug.LogError("ModelManager not found");
            }
            var model = mm.getById(port.defaultId);
            
            if (model.mesh == null)
            {
                Debug.LogError("Default Mesh Not Found, destoying child");
                Object.Destroy(child);
                continue;
            }
            Debug.Log($"Loaded Default Mesh: {model.mesh.name}");
            //set mesh
            var meshFilter = child.AddComponent<MeshFilter>();
            meshFilter.mesh = model.mesh;
            meshFilter.sharedMesh = model.mesh;
            //set material
            var meshRenderer = child.AddComponent<MeshRenderer>();
            meshRenderer.material = model.material;
            
            child.transform.SetParent(parent.transform); //makes this an actual child
            port.apply(child.transform); // move to correct position
            ret.Add(child); // i debugged 1.5 hours for this
        }
        
        return ret;
    }
    
    
}