package data.scripts.weapons;

import com.fs.starfarer.api.Global;
import com.fs.starfarer.api.combat.CombatEngineAPI;
import com.fs.starfarer.api.combat.CombatEntityAPI;
import com.fs.starfarer.api.combat.DamageType;
import com.fs.starfarer.api.combat.DamagingProjectileAPI;
import com.fs.starfarer.api.combat.OnHitEffectPlugin;
import com.fs.starfarer.api.util.Misc;
import data.scripts.util.SWP_Util;
import java.awt.Color;
import org.dark.shaders.light.LightShader;
import org.dark.shaders.light.StandardLight;
import org.lazywizard.lazylib.MathUtils;
import org.lazywizard.lazylib.combat.entities.SimpleEntity;
import org.lwjgl.util.vector.Vector2f;

public class SWP_LightningGunOnHitEffect implements OnHitEffectPlugin {

    private static final Vector2f ZERO = new Vector2f();

    @Override
    public void onHit(DamagingProjectileAPI projectile, CombatEntityAPI target, Vector2f point, boolean shieldHit, CombatEngineAPI engine) {
        if (point == null) {
            return;
        }
        if (projectile.getWeapon() == null) {
            return;
        }

        Vector2f origin = new Vector2f(projectile.getWeapon().getLocation());
        Vector2f slope = new Vector2f();
        slope.x = (point.x - origin.x);
        slope.y = (point.y - origin.y);
        Misc.normalise(slope);
        origin.x += slope.x * 5f;
        origin.y += slope.y * 5f;

        float distance = MathUtils.getDistance(origin, point);
        if (distance < 0.1f) {
            distance = 10f;
        }
        float range = projectile.getWeapon().getRange() * 2f;
        if (distance > range) {
            point.x = origin.x + (point.x - origin.x) * range / distance;
            point.y = origin.y + (point.y - origin.y) * range / distance;
        }

        int brightness = (int) (255f * Math.max(Math.min((range - distance) / distance, 0f), 1f));

        Global.getSoundPlayer().playSound("swp_lightning_gun_arc", 1f, 0.55f, point, ZERO);

        StandardLight light = new StandardLight(origin, point, ZERO, ZERO, null);
        light.setIntensity(0.65f);
        light.setSize(80f);
        light.setColor(0.65f, 0.75f, 0.9f);
        light.fadeOut(0.75f);
        LightShader.addLight(light);

        engine.spawnEmpArc(projectile.getSource(), origin, null, new SimpleEntity(point), DamageType.ENERGY, 0.0f, 0.0f, 100000f, null, 20f * Math.max(Math.min(
                (range - distance) / distance, 0f), 1f), new Color(100, 125, 200, SWP_Util.clamp255(brightness)),
                new Color(240, 250, 255, SWP_Util.clamp255(brightness)));
    }
}
