using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

/// <summary>
/// Class for player grabbing player interaction
/// </summary>
public class interactCaster : MonoBehaviour {
    private RaycastHit hit;
    private bool attached = false;
    GameObject other;
	RigidbodyFirstPersonController otherController;
    private int playerNumber;
    RigidbodyFirstPersonController myController;
    float gravitySign;


    bool getAttached() {
		return attached;
	}

	// Use this for initialization
    void Start () {
        myController = this.GetComponentInParent<RigidbodyFirstPersonController>();
        playerNumber = myController.playerNumber;
        bool isInverted = myController.isInverted;
        gravitySign = isInverted ? 1.0f : -1.0f;

    }
	
	

    void Update ()
    {
        if (Input.GetButtonDown("Grab" + playerNumber))
        {
            if (attached)
            {
                attached = false;
                other.transform.parent = null;
				if (otherController != null) {
					otherController.setAttached (attached);
					myController.setCarryWeight( new Vector3 (0, 0, 0));
				}
            }
            else
            {
                if (Physics.Raycast(transform.position, transform.up * gravitySign, out hit, 4))
                {
                    if (hit.collider.gameObject.CompareTag("Player"))
                    {
                        print("Grab raycast hit other player.");
                        attached = true;
                        other = hit.collider.gameObject;
						otherController = other.GetComponent (typeof(RigidbodyFirstPersonController)) as RigidbodyFirstPersonController;
						if (otherController != null) {
							otherController.setAttached (attached);
                            //other.GetComponentInChildren<interactCaster>().attached = true; Räjäyttää asioita!!!
							myController.setCarryWeight(otherController.determineGravity ());
						}
                    }
                }
            }
        }
        if (attached)
        {
            if (otherController.determineGravity().y < myController.determineGravity().y)
            {
                other.transform.parent = this.transform;
                other.transform.position = this.transform.position + new Vector3(0, 0.5f * -gravitySign, 0);
            }
            else
            {
                /*myController.transform.parent = other.transform;
                myController.transform.position = other.transform.position + new Vector3(0, 0.5f * gravitySign, 0);*/
            }
        }
}
}
