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

public class TransportObject : MonoBehaviour {

    private Collider entryPoint;
    private bool isSend = false;
    private PlayerController playerObject;
    private Renderer parentRenderer;
    private GameObject tube;

    public bool isRecive = false;
    //learp velocity
    public float velocity = 1f;
    //Time to teleport in seconds
    public float delayTime = 2f;
    public Transform outPoint;
    public string[] tags;
    public Material onMaterial;
    public Material offMaterial;
	public int state;

    // Use this for initialization
    void Start () {
        tube = transform.parent.GetChild(0).gameObject;
        entryPoint = GetComponent<Collider>();
        parentRenderer = transform.parent.GetComponent<Renderer>();
    }


    private void OnTriggerStay(Collider other)
    {
		if (state == 1 && other.gameObject.tag != "CubeCircuit") {
			parentRenderer.material = onMaterial;
			tube.SetActive (true);
			playerObject = other.transform.GetComponent<PlayerController> ();
			if (!isRecive) {
				for (int i = 0; i < tags.Length; i++) {
					if (other.CompareTag (tags [i])) {
						playerObject.setStop (true);
						StartCoroutine (transportPlayer (other));
						playerObject.transform.position = transform.position;
					}
				}
			}
		}

		if (other.gameObject.tag == "CubeCircuit") {
			if (other.gameObject.GetComponent<CircuitCube> ().state == 1) {
				state = 1;
			}
		}
    }

    float sumPosition (Vector3 array)
    {
        float sum = array.x + array.y + array.z;
        return sum;
    }

    void OnTriggerExit(Collider other)
    {
        if (!isSend)
        {
            isSend = false;
            isRecive = false;
            outPoint.GetComponent<TransportObject>().isRecive = false;
            outPoint.GetComponent<TransportObject>().isSend = false;
        }
        parentRenderer.material = offMaterial;
        tube.SetActive(false);
    }

    IEnumerator transportPlayer(Collider other)
    {
        yield return new WaitForSeconds(delayTime);
        isSend = true;
        outPoint.GetComponent<TransportObject>().isRecive = true;
        other.transform.position = outPoint.position;
        playerObject.setStop(false);
        parentRenderer.material = offMaterial;
        tube.SetActive(false);

        // other.transform.position = Vector3.Lerp(transform.position, outPoint.position , Time.deltaTime * 2);
    }

}
