using UnityEngine;

public class Door : MonoBehaviour
{
	public bool open = false;
	public bool locked = false;
	public float openTime = 1.0f;
	public float autoCloseTime = 3.0f;
	public Item key;

	float openAmount = 0;
	float closeTimer = 0;
	Vector3 origin;

	void Awake() {
		origin = transform.position;
	}

	void Start() {
		// Insta-open on level start.
		openAmount = open ? 1.0f : 0.0f;
	}

	void Update()
    {
		if (!open)
			closeTimer = 0;

		if (open && !locked) {
			// Close again after use.
			closeTimer += Time.deltaTime;
			if (closeTimer >= autoCloseTime)
				open = false;
		}

		if (open)
			openAmount = Mathf.Clamp01(openAmount + Time.deltaTime/openTime);
		else
			openAmount = Mathf.Clamp01(openAmount - Time.deltaTime/openTime);

		transform.position = origin + transform.right*openAmount;
	}

	void OnCollisionStay(Collision collision) {
		GameObject g = collision.gameObject;
		Entity entity = g.GetComponent<Entity>();
		PlayerControl pc = g.GetComponent<PlayerControl>();

		if (!locked && entity && entity.canMove) {
			open = true;
		}

		if (locked && pc && pc.enabled) {
			if (entity.Pay(key, 1))
				open = true;
		}
	}
}
