using UnityEngine;

public class GravityAttractor : MonoBehaviour
{
    public enum PlanetType
    {
        Gas = 0,
        Stone = 1,
        Lava = 2,
        Sun = 3
    }

    public Light LightSource;
    public PlanetType Type;
    public Material[] Materials;
    public float Gravity = -9.8f;
    public Color LavaColor;
    public Color SunColor;

    public void SetType(PlanetType type)
    {
        Type = type;
        name = NameParser.Instance.GetRandomName();

        switch (Type)
        {
            case PlanetType.Gas:
                Gravity = Random.Range(-6f, -7f);
                LightSource.gameObject.SetActive(false);
                transform.localScale = transform.localScale * (Mathf.InverseLerp(-6f, -7f, Gravity) + 1);
                break;
            case PlanetType.Stone:
                Gravity = Random.Range(-7f, -11f);
                LightSource.gameObject.SetActive(false);
                transform.localScale = transform.localScale * (Mathf.InverseLerp(-7f, -11f, Gravity) + 1);
                break;
            case PlanetType.Lava:
                Gravity = Random.Range(-11f, -13f);
                LightSource.gameObject.SetActive(true);
                LightSource.color = LavaColor;
                LightSource.range = 100;
                transform.localScale = transform.localScale * (Mathf.InverseLerp(-11f, -13f, Gravity) + 1);
                break;
            case PlanetType.Sun:
                Gravity = Random.Range(-13f, -15f);
                LightSource.gameObject.SetActive(true);
                LightSource.color = SunColor;
                LightSource.range = 250;
                transform.localScale = transform.localScale * (Mathf.InverseLerp(-13f, -15f, Gravity) + 1);
                break;
        }

        var renderer = GetComponent<Renderer>();
        renderer.material = Materials[(int)Type];
        renderer.material.mainTextureOffset = new Vector2(Random.Range(0f, 1f), Random.Range(0f, 1f));
        renderer.material.mainTextureScale = new Vector2(Random.Range(0.2f, 1f), Random.Range(0.2f, 1f));

    }

    public void Attract(Rigidbody body)
    {
        Vector3 gravityUp = (body.position - transform.position).normalized;
        Vector3 localUp = body.transform.up;

        body.AddForce(gravityUp * Gravity * 1.35f);

        var targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * body.rotation;
        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 0.1f);
    }
}
