//#define GRABER_DEBUG
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterGraber : MonoBehaviour {

    protected Character controller;

    private GrabableObject objectInRange;
    private GrabableObject holdingObject;

    public virtual void PrepareGrabber (Character controller) {
        this.controller = controller;
    }

    public void Grab () {
        if (this.objectInRange) {
            this.objectInRange.GrabObject(this.controller.gameObject);
            this.holdingObject = this.objectInRange;
            this.objectInRange = null;

            if (this.controller is Player) {
                (this.controller as Player).HasAntena = true;
                this.controller.Movement.IsSlowerDown = true;

                var gc = GameObject.FindObjectOfType<GameController>();
                if (gc) { 
                    gc.UIController.GameplayView.CurrentGoalText.text = "Place antenna in a place with the best signal!";
                }
            }
        }
    }

    public void Drop () {
        if (this.holdingObject) {
            this.holdingObject.DropObject();
            this.objectInRange = this.holdingObject;
            this.holdingObject = null;

            if (this.controller is Player) {
                (this.controller as Player).HasAntena = false;
                this.controller.Movement.IsSlowerDown = false;

                var gc = GameObject.FindObjectOfType<GameController>();
                if (gc) {
                    if (gc.MapPortal.gameObject.activeInHierarchy) {
                        gc.UIController.GameplayView.CurrentGoalText.text = "Find portal to escape from Zombie horde!";
                    } else {
                        gc.UIController.GameplayView.CurrentGoalText.text = "Find antenna and avoid Zombies!";
                    }
                }
            }
        }
    }

    void OnTriggerEnter(Collider other) {
        if (this.controller is Zombie) {
            return;
        }

        var grabable = other.GetComponent<GrabableObject>();
        if (grabable) {
#if GRABER_DEBUG
            Debug.Log("[GRABER] has something to grab");
#endif
            objectInRange = grabable;
        }
    }

    void OnTriggerExit(Collider other) {
        if (this.controller is Zombie) {
            return;
        }

        var grabable = other.GetComponent<GrabableObject>();
        if (grabable) {
#if GRABER_DEBUG
            Debug.Log("[GRABER] nothing to grab");
#endif
            objectInRange = null;
        }
    }
}
