using UnityEngine;
using ScrambleKit.FX;
using ScrambleKit.Hits;

namespace ScrambleKit.Weapons
{
    [RequireComponent(typeof(WeaponCore))]
    public class Gun : MonoBehaviour
    {

        public Transform ProjectilePrefab;
        public float MuzzleVelocity=20;
        public Transform MuzzleFlashPrefab;
        public float KickBackSpeed = 2f;
        public float RumbleTime = 0.03f;
        public float RumbleSize = 0.005f;

        public Transform FirePoint;

        private WeaponCore core;

        void Attack()
        {
            if(core.IsReady)
                Fire();
        }

        private void Fire()
        {
            if (ProjectilePrefab == null)
                return;

            ShotJuiceFX();
            LaunchProjectile();
        }

        private void ShotJuiceFX()
        {
            SpawnMuzzleFlash();
            KickBack();
            CameraFX.Rumble(RumbleTime, RumbleSize);
        }

        private void KickBack()
        {
            Vector2 fireDir = (FirePoint.position - transform.root.position).normalized;
            HitInfo kickBack = HitInfo.BuildSimplePush(-fireDir, KickBackSpeed);
            transform.root.SendMessage("TakeHit", kickBack, SendMessageOptions.DontRequireReceiver);
        }

        private void SpawnMuzzleFlash()
        {
            if (MuzzleFlashPrefab == null)
                return;

            Transform flash = Instantiate(MuzzleFlashPrefab);
            flash.position = FirePoint.position;
            flash.localEulerAngles = transform.localEulerAngles;
        }

        private void LaunchProjectile()
        {
            Transform proj = Instantiate(ProjectilePrefab);
            Rigidbody2D rb = proj.GetComponent<Rigidbody2D>();

            proj.position = FirePoint.position;
            proj.localEulerAngles = transform.localEulerAngles;
            Vector2 accel = MuzzleVelocity * FirePoint.up.normalized;
            Vector2 force = rb.mass * accel;
            rb.AddForce(force, ForceMode2D.Impulse);
        }


        void Start()
        {
            core = GetComponent<WeaponCore>();

            if (ProjectilePrefab == null)
                Debug.LogError("ERROR: Gun " + name + " does not have a projectile prefab assigned");
            if (FirePoint == null)
                Debug.LogError("ERROR: Gun " + name + " does not have a FirePoint assigned. Create an empty child of the gun that represents where to fire from, and drag it onto the gun's FirePoint property.");
        }
    }
}