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

public class FuelPickup : MonoBehaviour
{
    public float sensorRadius = 2;
    public float shrinkSpeed = 0.1f;
    private Vector3 defaultSize;
    private SpriteRenderer spriteRenderer;
    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        defaultSize =transform.localScale;

        Reposition();
    }

    // Update is called once per frame
    void Update()
    {
        if(!isActive){return;}
        Collider2D[] overlaps = Physics2D.OverlapCircleAll(transform.position, sensorRadius);
        foreach(Collider2D overlap in overlaps){
            if(overlap!=null){
                if(overlap.tag == "Player"){
                    //Collect
                    isActive=false;
                    StartCoroutine(Collect());
                    
                    FuelManager.instance.Refill();
                }
            }
        }
        
    }

    bool isActive = true;
    IEnumerator Collect(){
        while(spriteRenderer.color.a > 0.2f){
            transform.localScale = Vector3.Lerp(transform.localScale, Vector3.zero, shrinkSpeed);
            spriteRenderer.color = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, Mathf.Lerp(spriteRenderer.color.a,0,shrinkSpeed));
            yield return new WaitForEndOfFrame();
        }

        //Goto next position
        Reposition();
        isActive=true;
    }


    public void Reposition(){
        transform.localScale = defaultSize;
        spriteRenderer.color = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, 1);
        int carIndex= (int)(carController.instance.transform.position.x / LevelGenerator.instance.xMultiplier);
        float gap = Mathf.Clamp((carController.instance.transform.position.x / 2500f) * 150, 15,100);
        Debug.Log(gap);
        transform.position = LevelGenerator.instance.points[carIndex + (int)gap] + new Vector3(0,2);
    }

    void OnDrawGizmos(){
        Gizmos.DrawWireSphere(transform.position, sensorRadius);
    }
}
