using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Saltosion.OneWeapon.Player;
using Saltosion.OneWeapon.Enemies;
using Saltosion.OneWeapon.Effects;
using Saltosion.OneWeapon.Environment;

namespace Saltosion.OneWeapon.Guns {
    [RequireComponent(typeof(Bullet), typeof(CustomLight))]
    public class RegularBullet : MonoBehaviour {

        public Rigidbody2D Body;
        public GameObject Sprite;

        public ParticleSystem Trail;
        public ParticleSystem Explosion;

        public float Damage = 12;
        public float Speed = 15;

        private float DeathTimer = 0;

        private Bullet Bullet;
        private CustomLight Light;

        void Start() {
            Bullet = GetComponent<Bullet>();
            Light = GetComponent<CustomLight>();
            Vector2 Direction = Bullet.Direction;
            float Rot = Bullet.InitialRotation;

            Light.LightIntensity = 1.1f;

            Body.velocity = Direction * Speed;
            Body.rotation = Rot - 90;

            Explosion.Stop();
        }

        void Update() {
            DeathTimer += Time.deltaTime;
            if (DeathTimer > 20) {
                Destroy(gameObject);
            }
            if (DeathTimer > 19) {
                Light.LightIntensity = Mathf.Max(2 - (DeathTimer - 19f) * 10, 0);
            }
        }

        void OnTriggerEnter2D(Collider2D collider) {
            if (collider.GetComponent<PlayerController>() != null) {
                // don't hit the player!
                return;
            }
            Bullet.HasExploded = true;

            Destroy(Sprite);
            Destroy(Body);
            Destroy(GetComponent<CapsuleCollider2D>());
            Light.LightSize = 4;
            Explosion.Play();
            Trail.Stop();
            DeathTimer = 19;

            // Do damage here, kill everyone
            Bullet.DoDamage(Damage, 1, collider, Bullet.Direction);
        }
    }
}
