using UnityEngine;

public class InteractableObject : MonoBehaviour {

    protected float maxDistance = 4f;

    protected static Shader highlightShader = null;

    protected Shader originalShader = null;

    protected Material myMat = null;

    private Collider myCollider;

    protected bool isVisible = false;

    private Ray ray;

    private RaycastHit hit;

    private bool hasClickedOnMe = false;

	protected virtual void Start () {
        highlightShader = Resources.Load<Shader>("Shaders/Highlight");
        myMat = GetComponent<Renderer>().material;
        originalShader = myMat.shader;
        myCollider = GetComponent<Collider>();
    }

    protected virtual void Update() {
        if (isVisible && !FenteTelescope.isInTelescope && Camera.main != null) {
            ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
            if (Physics.Raycast(ray, out hit, maxDistance) && hit.collider == myCollider) {
                myMat.shader = highlightShader;
                if (Input.GetMouseButtonDown(0) || Input.GetButtonDown("Action")) {
                    hasClickedOnMe = true;
                    DoActionDown();
                }
                else if (Input.GetMouseButtonUp(0) || Input.GetButtonUp("Action")) {
                    hasClickedOnMe = false;
                    DoActionUp();
                }
                else if (Input.GetMouseButton(0) || Input.GetButton("Action")){
                    DoAction();
                }
            } else {
                myMat.shader = originalShader;
            }
        }
        if (hasClickedOnMe && Input.GetMouseButtonUp(0) && !FenteTelescope.isInTelescope)
        {
            hasClickedOnMe = false;
            DoActionUp();
        }
    }

    protected void OnBecameVisible() {
        isVisible = true;
    }

    protected void OnBecameInvisible() {
        isVisible = false;
    }

    protected virtual void DoActionDown() {
        
    }

    protected virtual void DoActionUp() {
        
    }
    protected virtual void DoAction( ){ 

    }
    protected virtual void MoveTelescop() {

    }
}