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

public class DragablePin : MonoBehaviour
{
    protected float OffsetX;
    protected float OffsetY;
    public RectTransform[] pins;
    public DragablePin Linked;
    public bool master = false;
    public UILineRenderer wire;
    public int current;

    // Use this for initialization
    void Start()
    {
        if (master)
        {
            Vector2[] positions = new Vector2[2];
            positions[0] =  GetComponent<RectTransform>().localPosition;
            positions[1] = Linked.GetComponent<RectTransform>().localPosition;
            wire.Points = (positions);
            wire.SetVerticesDirty();
        }
        LockOn();
    }

    // Update is called once per frame
    void Update()
    {
        if (master)
        {
            Vector2[] positions = new Vector2[2];
            positions[0] =  GetComponent<RectTransform>().localPosition;
            positions[1] =  Linked.GetComponent<RectTransform>().localPosition;
            wire.Points = (positions);
            wire.SetVerticesDirty();
        }
    }

    public void BeginDrag()
    {
        OffsetX = transform.position.x - Input.mousePosition.x;
        OffsetY = transform.position.y - Input.mousePosition.y;
    }

    public void OnDrag()
    {
        transform.position = new Vector3(OffsetX + Input.mousePosition.x, OffsetY + Input.mousePosition.y);
        
    } 

    public void LockOn()
    {
        for (int i = 0; i < pins.Length; i++)
        {
            if (RectTransformUtility.RectangleContainsScreenPoint(pins[i], GetComponent<RectTransform>().position))
            {
                GetComponent<RectTransform>().position = pins[i].position;
                current = i;
            }
        }
    }
}
