using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Removable))]

public class Bullet : MonoBehaviour {

    private Removable _remover;
    private Transform _transform;
    private float _startTime;
    private Vector3 _lastPosition;
    [SerializeField] private float _lifeTime = 5;
    [SerializeField] private float _speed = 100;
    public int fraction;

	void Start () {
        _startTime = Time.time;
        _transform = transform;
        _lastPosition = _transform.position;
        _remover = GetComponent<Removable>();
	}
	
	void Update () {
        _transform.position += (_transform.rotation * Vector3.forward) * Time.deltaTime * _speed;
        if (Time.time - _startTime > _lifeTime)
            _remover.Remove();

        RaycastHit hitInfo;

        var dir = _transform.position - _lastPosition;
        if (Physics.Raycast(_lastPosition, dir.normalized, out hitInfo, dir.magnitude))
        {
            var tank = hitInfo.rigidbody ? hitInfo.rigidbody.gameObject.GetComponent<Tank>() : null;
            if (tank){
                if (tank.fraction != fraction)
                    tank.Hit();

            } else {
                var remover = hitInfo.collider.gameObject.GetComponent<Removable>();
                if (remover)
                    remover.Remove();
            }

            _remover.Remove();
        }

        _lastPosition = _transform.position;

    }
	


}
