using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class BulletScript : MonoBehaviour
{
    public DataBullet dataBullet;

    private float damage;
    private float speed;
    private int ammo;

    public GameObject particalClash;
    
    public float lifetime = 3f;
    private Rigidbody rb;

    private Vector3 direction;

    private float time = 0f;

    private Ray ray;
    private RaycastHit hit;

    /// <summary>
    /// Sobald life Time vorbei ist Destroy die Bullet.
    /// </summary>
    /// <param name="lifetime">Lifetime der Bullet</param>
    private void die(float lifetime){
        if(time > lifetime){
            GameObject.Destroy(this.gameObject);
        }
    }
    private void CheckForColliders(){
        if(Physics.Raycast(ray, out hit)){ //wenn true wird durch out in variable hit ein RayCastHit gespeichert
            direction = hit.point - transform.position;//Richtung in die, die Kugel fliegt
        }
    }
    /// <summary>
    /// clashPartical spawned clashPartical am EinschlagPunkt der Kugel.
    /// </summary>
    /// <param name="collision">Die Collision mit der Bullet.</param>
    public void clashPartcal(Collision collision){
        ContactPoint contact = collision.GetContact(0);
        Instantiate(particalClash,transform.position,Quaternion.LookRotation(contact.normal));
    }
    /// <summary>
    /// Wenn die Bullet etwas behrührt zerstört sie sich selbst.
    /// </summary>
    /// <param name="collision">Die Collision mit der Bullet</param>
    private void OnCollisionEnter(Collision collision){
        Debug.Log(collision.gameObject.name + " UND HIER IST DER TAG: " + collision.gameObject.tag);
        if(collision.transform.tag == "Enemy"){
            collision.transform.GetComponent<Enemy>().takeDamage(damage);
        }
        clashPartcal(collision);
        GameObject.Destroy(this.gameObject);
        
    }
    // Start is called before the first frame update
    void Start()
    {
        damage = dataBullet.damage;
        ammo = dataBullet.ammo;
        speed = dataBullet.speed;

        rb = this.GetComponent<Rigidbody>();
        
    
        
        ray = Camera.main.ViewportPointToRay(new Vector3(0.5f,0.5f,0f));
        CheckForColliders();
    }
    

    // Update is called once per frame
    void Update()
    {
        rb.velocity = direction.normalized * speed;
        die(lifetime);
        time += Time.deltaTime;
    }
}
