using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Star : MonoBehaviour
{
    public Transform clouds;

    ParticleSystem particles;

    bool isTrailing;

    Vector3 movementDirection;

    float spawnTimer = -1f;
    float spawnFinalScale;

    const float speed = 150f;
    const float spawnDuration = 0.1f;

    void Awake()
    {
        particles = GetComponentInChildren<ParticleSystem>();
    }

    public void Init(bool spawn = false)
    {
        particles.Pause();
        Vector3 spawnPos = Vector3.zero;
        while(spawnPos.sqrMagnitude < 64f)
        {
            spawnPos = new Vector3(Random.Range(-StarsManager.spawnMaxX, StarsManager.spawnMaxX),
                Random.Range(-StarsManager.spawnMaxY, StarsManager.spawnMaxY),
                0);
                //Random.Range(-StarsManager.spawnMaxZ, StarsManager.spawnMaxZ));
        }
        movementDirection = spawnPos.normalized;
        transform.localPosition = spawnPos;
        spawnFinalScale = Random.Range(0.18f, 0.25f);
        transform.localScale = Vector3.one * (spawn ? 0.001f : spawnFinalScale);
        particles.Play();
        if(spawn)
        {
            spawnTimer = spawnDuration * Random.Range(0.9f, 1.1f);
        }
    }
	
	// Update is called once per frame
	void Update ()
    {
        if(isTrailing)
        {
            //transform.localPosition = transform.localPosition - Vector3.forward * speed * Time.deltaTime;
            transform.localPosition = transform.localPosition + movementDirection * speed * Time.deltaTime;
            if(IsOut())
            {
                isTrailing = false;
            }
        }
        if(spawnTimer > 0)
        {
            spawnTimer -= Time.deltaTime;
            float progress = Mathf.Clamp01(1f - spawnTimer / spawnDuration);
            progress *= progress;
            if(progress <= 0.7f)
            {
                progress *= 2f / 0.7f;
            }
            else
            {
                progress = 2f - (progress - 0.7f) / 0.3f;
            }
            transform.localScale = Vector3.one * spawnFinalScale * progress;
        }

        if(clouds != null)
        {
            clouds.transform.localRotation = Quaternion.Euler(clouds.transform.localRotation.eulerAngles + new Vector3(0, Time.deltaTime * 3f, 0));
        }
	}

    public void TriggerTrail(float duration)
    {
        if(IsOut())
        {
            Init();
        }

        isTrailing = true;
        ParticleSystem.MainModule main = particles.main;
        main.startLifetime = duration;
    }

    public void TriggerSpawn()
    {
        spawnTimer = spawnDuration * Random.Range(0.9f, 1.1f);
        spawnFinalScale = 1f;
    }

    bool IsOut()
    {
        return transform.localPosition.sqrMagnitude > 1.5f * (StarsManager.spawnMaxX * StarsManager.spawnMaxX + StarsManager.spawnMaxY * StarsManager.spawnMaxY);
    }
}
