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

public class AutoJointer : MonoBehaviour {

    private void Awake()
    {
        //print("mulkku?");
    }

    // Use this for initialization
    void Start () {
        //print("doinn");
        GameObject[] go = GameObject.FindGameObjectsWithTag("JointPos");
        foreach (GameObject g in go)
        {
            if (g == gameObject) continue;
            //if (!(gameObject.name == "Jointer" && g.gameObject.name == "Jointer (1)")) continue;
            if (g.GetHashCode() > gameObject.GetHashCode()) // only the guy with the bigger hash code should make a hinge
            {
                Vector2 myrealpos = transform.position; // transform.parent.TransformPoint(transform.position);

                Vector2 otherrealpos = g.transform.position; // parent.TransformPoint(g.transform.position);
                //print(gameObject.name.ToString() + " at " + myrealpos.ToString());
                //print(g.gameObject.name + " at " + otherrealpos.ToString());
                Vector2 diff = myrealpos - otherrealpos;
                //print(diff);
                if (diff.magnitude < 1.2f)
                {
                    /*print(diff);
                    // transform.position is the position relative to parent
                    print(transform.position);
                    print("m ie");
                    print(gameObject.name);*/

                    DistanceJoint2D dj2d = transform.parent.gameObject.AddComponent<DistanceJoint2D>();
                    //dj2d.autoConfigureDistance = false;
                    //dj2d
                    dj2d.connectedBody = g.transform.parent.GetComponent<Rigidbody2D>();
                    dj2d.autoConfigureDistance = true;
                    dj2d.autoConfigureConnectedAnchor = false;
                    dj2d.anchor = transform.localPosition;
                    dj2d.connectedAnchor = g.transform.parent.InverseTransformPoint(transform.position);
                    //dj2d.distance = 0f;
                    //print("connected");
                    //print(g.gameObject.name);
                }
            } 
        }
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}
