using System;
using System.Linq;
using UnityEngine;

public sealed class PlanetsView : MonoBehaviour
{
    [SerializeField]
    private GameObject starPrefab = null;
    [SerializeField]
    private GameObject planetPrefab = null;
    [SerializeField]
    private float scale = 1;

    [SerializeField]
    private PlanetData[] planets = new PlanetData[] {
        new PlanetData(Vector3.zero, 2),
        new PlanetData(Vector3.forward * 5, 1),
        new PlanetData(Vector3.back * 7, 0.5f),
        new PlanetData(Vector3.left * 5, 1),
        new PlanetData(Vector3.right * 6, 0.6f),
        new PlanetData(Vector3.forward * 10, 0.3f),
        new PlanetData(Vector3.back * 12, 0.8f),
        new PlanetData(Vector3.left * 16, 0.6f),
        new PlanetData(Vector3.right * 18, 1.2f)
    };

    private GameObject[] planetViews = null;

    [Serializable]
    public sealed class PlanetData {
        [SerializeField]
        public Vector3 Position;
        [SerializeField]
        public float Radius;
        [SerializeField]
        public Color Color;
        [SerializeField]
        public bool IsStar;
        public PlanetData() {}
        public PlanetData(Vector3 position, float radius, bool isStar = false) {
            Position = position;
            Radius = radius;
            Color = Color.white;
            IsStar = isStar;
        }
        public PlanetData(Vector3 position, float radius, Color color, bool isStar = false)
        {
            Position = position;
            Radius = radius;
            Color = color;
            IsStar = isStar;
        }
    }

    public void SetPlanets(PlanetData[] data)
    {
        if (planetViews != null)
        {
            foreach (var planet in planetViews)
                Destroy(planet);
        }
        planets = data ?? Array.Empty<PlanetData>();
        CreatePlanets(planets);
    }

    private void Start()
    {
        if (planetViews == null)
            CreatePlanets(planets);
    }

    private void CreatePlanets(PlanetData[] data)
    {
        planetViews = data.Select(CreatePlanet).ToArray();
    }

    private GameObject CreatePlanet(PlanetData data)
    {
        var planet = Instantiate(data.IsStar ? starPrefab : planetPrefab, transform);
        planet.transform.localPosition = data.Position * scale;
        planet.transform.localScale = Vector3.one * data.Radius * scale;
        planet.GetComponent<MeshRenderer>().material.color = data.Color;
        // Debug.LogError("set color " + data.Color);
        return planet;
    }
}
