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

public class Vanisher : MonoBehaviour
{
    [SerializeField]
    private float timeToVanish;
    [SerializeField]
    private float timeToAppear;
    [SerializeField]
    private float magnitude;
    private float timer = 0;
    private GrappleHook grapple;
    private bool isVanishing = false;
    private Vector3 originalPos;
    //TODO represent obj is breaking

    private void Start() {
        originalPos = transform.localPosition;
    }
    private void Update() {
        timer += Time.deltaTime;
        if(isVanishing){//Shake
            float speed = timer / timeToVanish;
            float x = Random.Range(-.5f, .5f) * speed * magnitude/100;
            float y = Random.Range(-.5f, .5f) * speed * magnitude/100;
            transform.localPosition += new Vector3(x, y, originalPos.z);
        }
        
    }
    public void Begin(GrappleHook grapple){
        this.grapple = grapple;
        if(isVanishing)return;
        Invoke("Vanish", timeToVanish);
        isVanishing = true;
        originalPos = transform.localPosition;
        timer = 0;
    }

    private void Vanish(){
        grapple?.Unhook(this.gameObject);
        gameObject.SetActive(false);
        Invoke("Appear", timeToAppear);
        isVanishing = false;
        timer = 0;
        transform.localPosition = originalPos;
    }

    private void Appear(){
        gameObject.SetActive(true);
    }

    private void OnCollisionEnter(Collision other) {
        if(other.gameObject.tag.Equals("Player")){
            Begin(other.gameObject.GetComponent<GrappleHook>());
        }
    }
    private void OnCollisionExit(Collision other) {
        if(other.gameObject.tag.Equals("Player")){
            if(!grapple.HookedTo.Equals(this.gameObject)){
                grapple = null;
            }
        }
        
    }
}
