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

public enum plugType
{
	USB,
	USBC,
	HDMI,
	DISPLAY,
	VGA,
	AUDIO
}

[RequireComponent(typeof (Rigidbody))]
public class PlugScript : MonoBehaviour {

	public plugType plug = plugType.USB;
	[HideInInspector] public bool pluggedIn = false;
	/*[HideInInspector]*/ public int signalReceivedPlug = -1;
	private InteractionScript _interactionScript;
	public CableScript _attachedCable;


	void Start () {
		_interactionScript = GameObject.FindGameObjectWithTag ("Player").GetComponent<InteractionScript> ();
	}


	public void PlugIn(Transform socket){
		_interactionScript.dropObject ();
		this.transform.position = socket.position;
		this.transform.rotation = socket.rotation;
		this.GetComponent<BoxCollider> ().isTrigger = true;
		this.GetComponent<Rigidbody> ().constraints = RigidbodyConstraints.FreezeAll;

		pluggedIn = true;
		socket.gameObject.GetComponent<SocketScript> ().connected = true;
		socket.gameObject.GetComponent<SocketScript> ().connectedTo = this.gameObject;

		//Signalweiterleitung durch SocketScript
	}

	public void PlugOut(Transform socket){
		this.GetComponent<BoxCollider> ().isTrigger = false;
		this.GetComponent<Rigidbody> ().constraints = RigidbodyConstraints.None;

		pluggedIn = false;
		socket.gameObject.GetComponent<SocketScript> ().connected = false;
		socket.gameObject.GetComponent<SocketScript> ().connectedTo = null;

		_attachedCable.Reset ();
	}

	public bool CheckOrientation(Transform socket){
		if (!socket.gameObject.GetComponent<SocketScript> ().symmetrical) {
			if (Mathf.Abs(Vector3.Angle(transform.up, socket.transform.up)) < 30 && Mathf.Abs(Vector3.Angle(transform.right, socket.transform.right)) < 30) {
				return true;
			} else {
				return false;
			}
		} else {
			if (Mathf.Abs(Vector3.Angle(transform.up, socket.transform.up)) < 30) {
				return true;
			} else {
				return false;
			}
		}
	}

	void OnTriggerEnter(Collider other){
		if (this.gameObject == _interactionScript.objectHeld) {
			if (other.gameObject.CompareTag ("Socket") || other.gameObject.CompareTag ("SocketFixed")) {
				if (plug == other.gameObject.GetComponent<SocketScript> ().requiredPlug) {
					Debug.Log ("Success" + this.gameObject.name);
					if (CheckOrientation(other.transform)) {
						PlugIn (other.transform);
					} else {
						Debug.Log ("Wrong Orientation " + Mathf.Abs(Vector3.Angle(transform.right, other.transform.right)));
					}
				} else {
					Debug.Log ("Fail" + other.gameObject.name);
				}
			}
		}
	}

	void OnTriggerExit(Collider other){
		if (this.gameObject == _interactionScript.objectHeld) {
			if (other.gameObject.CompareTag ("Socket") || other.gameObject.CompareTag ("SocketFixed")) {
				if (this.gameObject == other.gameObject.GetComponent<SocketScript>().connectedTo) {
					Debug.Log ("Plugging out " + this.gameObject.name);
					PlugOut (other.transform);
				} else {
					//do nothing
				}
			}
		}
	}
}
