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

public class PossessBullet : MonoBehaviour
{
    [SerializeField] private float stayTime = 5f;
    private Ticker lifeTicker;
    public float bulletSpeed = 10f;
    // private float maxDistance = 30f;
    // public LayerMask phobic;
    private Vector3 startingPosition;
    private Rigidbody rb;

    void Awake() {
        startingPosition = this.transform.position;
        rb = GetComponent<Rigidbody>();

        lifeTicker = new Ticker(stayTime);
        lifeTicker.onTick.AddListener(Expire);
    }

    void FixedUpdate() {
        float bulletTravel = Time.deltaTime * bulletSpeed;
        this.transform.position = Vector3.MoveTowards(this.transform.position, this.transform.position + this.transform.forward, bulletTravel);
    }

    void Update() {
        lifeTicker.Tick(Time.deltaTime);
    }

    public void Expire() {
        //Do Something
        Pool.Del(gameObject);
    }

    private void OnCollisionEnter(Collision other)
    {
        if(LayerMask.NameToLayer("Enemy") == other.gameObject.layer) {// and it hits an ENEMY...
            PlayerManager.I.unit.GetComponent<BasicWeapon>().owner = Ownership.ENEMY;
            PossessionManager.I.possessed = other.gameObject;
            Expire();//Destroy this bullet.
        }
        else//Otherwise...
            Physics.IgnoreCollision(other.collider, this.GetComponent<Collider>());
        // if (other.gameObject.GetComponent<UnitController>()) {
        //     PossessionManager.I.possessed = other.gameObject;
        //     Expire();
        // }
        // if (!phobic.AllowedLayer(other.gameObject.layer))
        //     Expire();
    }
}
