using UnityEngine;
using System.Collections;

public class VictimFinder : MonoBehaviour {
    public float maxDistance = 10f;
    public bool playerOtherwise = false;
    public GameObject victim;
    private GameManager gameManager;

    void Start() {
        gameManager = FindObjectOfType<GameManager>();
    }

    void Update() {
        detectVictim();
    }

    private void detectVictim() {
        RaycastHit hitInfoLeft;
        RaycastHit hitInfoRight;
        RaycastHit hitInfoNone = new RaycastHit();
        Physics.Raycast(transform.position, Vector3.left, out hitInfoLeft, maxDistance);
        Physics.Raycast(transform.position, Vector3.right, out hitInfoRight, maxDistance);

        if (hitInfoRight.collider != null && (hitInfoRight.collider.gameObject.tag == "Enemy" || hitInfoRight.collider.gameObject.tag == "Ground")) {
            hitInfoRight = hitInfoNone;
        }
        if (hitInfoLeft.collider != null && (hitInfoLeft.collider.gameObject.tag == "Enemy" || hitInfoLeft.collider.gameObject.tag == "Ground")) {
            hitInfoLeft = hitInfoNone;
        }

        if (hitInfoLeft.collider != null && hitInfoRight.collider != null) {
            victim = (hitInfoLeft.distance < hitInfoRight.distance) ? hitInfoLeft.collider.gameObject : hitInfoRight.collider.gameObject;
        } else if (hitInfoLeft.collider != null) {
            victim = hitInfoLeft.collider.gameObject;
        } else if (hitInfoRight.collider != null) {
            victim = hitInfoRight.collider.gameObject;
        } else if (playerOtherwise) {
            victim = gameManager.player;
        } else {
            victim = null;
        }
    }
}
