using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Drawer : MonoBehaviour
{
    public static Drawer instance {get;private set;}
    void Awake(){
        instance= this;
    }
    public LineRenderer lineRenderer;
    public PolygonCollider2D edgeCollider2D;
    List<Vector3> points = new List<Vector3>();

    public Slider drawingFuel;
    public float drawingFuelConsumption = 0.05f;


    bool dragging = false;
    public void OnMouseDown(BaseEventData e){
        if (drawn) { return; }
        PointerEventData ped = (PointerEventData) e as PointerEventData;
        
        dragging= true;
        startedPoint = ped.position;
        lineRenderer.SetPositions(new Vector3[0]);
        points = new List<Vector3>();

        drawn = true;
        GameManager.StartGame();

        // lineRenderer.transform.position = new Vector3(0, 0, 10);
        //lineRenderer.GetComponent<Rigidbody2D>().simulated = false;

    }


    Vector3 startedPoint = new Vector3();
    public void OnMouseDrag(BaseEventData e) { 
        if(drawingFuel.value <= 0){return;}
        PointerEventData ped = (PointerEventData) e as PointerEventData;
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(ped.position);
        if(points.Count> 0) {
            RaycastHit2D hit = Physics2D.Linecast(points[points.Count - 1], worldPos);
            if (hit.collider != null)
            {
                return;
            }
        }
        
        points.Add(worldPos);
        UpdateLine();

        drawingFuel.value -= drawingFuelConsumption;
    }

    public void OnMouseUp(BaseEventData e)
    {
        dragging= false;
        FinishDrawing();
    }


    void UpdateLine()
    {
        lineRenderer.positionCount = points.Count;
        lineRenderer.SetPositions(points.ToArray());

        
    }

    bool drawn = false;
    void FinishDrawing()
    {
        List<Vector2> points3 = new List<Vector2>();
        foreach(Vector2 point in points)
        {
            points3.Add(point);
        }
        for(int i= points.Count-1; i >0; i--)
        {
            points3.Add(points[i] + new Vector3(0.05f,0.1f,0));
        }
        //edgeCollider2D.SetPoints(points3);
        edgeCollider2D.SetPath(0, points3);
        edgeCollider2D.GetComponent<Rigidbody2D>().simulated = true;
        GameManager.Player.GetComponent<Rigidbody2D>().simulated=true;

    }

    void OnValidate()
    {
        if (edgeCollider2D == null)
        {
            edgeCollider2D = lineRenderer.GetComponent<PolygonCollider2D>();
        }
    }
}
