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

public class CheckpointOnTouch : MonoBehaviour
{
    Vector2 checkpoint;

    private void Start()
    {
        checkpoint = transform.position;
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            GetComponent<SinWaveMovement>().enabled = false;

            if (collision.gameObject.GetComponent<PlayerController>().respawnLocation == checkpoint)
            {
                return;
            }
            EventBus.Publish<CheckpointEvent>(new CheckpointEvent("Checkpoint!"));
            Color tmp = GetComponent<SpriteRenderer>().color;
            tmp.a = 1;
            GetComponent<SpriteRenderer>().color = tmp;
            collision.gameObject.GetComponent<PlayerController>().respawnLocation = checkpoint;            
            StartCoroutine(RiseAndPing());
        }
    }

    private IEnumerator RiseAndPing()
    {
        
        Vector2 destination = checkpoint + Vector2.up * 3f;
        while (Vector2.Distance(transform.position, destination) > 0.1f)
        {
            Debug.DrawLine(transform.position, destination);
            transform.position = Vector2.MoveTowards(transform.position, destination, 3*Time.deltaTime);
            yield return null;
        }
        transform.position = destination;

        int groundLayer = LayerMask.GetMask("Platform");
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 10f, groundLayer);
        LineRenderer lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.material = new Material(Shader.Find("Legacy Shaders/Particles/Alpha Blended Premultiply"));
        float alpha = 1.0f;
        Color startColor = GetComponent<SpriteRenderer>().color; ;
        Color endColor = hit.transform.gameObject.GetComponent<SpriteRenderer>().color; 
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(startColor, 0.0f), new GradientColorKey(endColor, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
        );
        lineRenderer.colorGradient = gradient;
        lineRenderer.SetPosition(0, transform.position);
        lineRenderer.SetPosition(1, hit.point);
        lineRenderer.startWidth = transform.localScale.x;
        lineRenderer.endWidth = 0.001f;
    }

}
public class CheckpointEvent
{
    public string checkpoint_msg = "";
    public CheckpointEvent(string _checkpoint_msg) { checkpoint_msg = _checkpoint_msg; }
}
