package mygame;

import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;

/**
 *
 * @author Snowsun
 */
public class PlayerShootControl extends AbstractControl implements ActionListener {

    private InputManager inputManager;
    private final float maxTimeToOverheat = 3f;
    private float timeToOverheat = maxTimeToOverheat;
    private boolean isShooting = false;

    public PlayerShootControl(InputManager inputmanager) {
        this.inputManager = inputmanager;
        initMappings();
    }

    @Override
    protected void controlUpdate(float tpf) {
        if (isShooting) {
            timeToOverheat -= tpf;
            if (timeToOverheat <= 0) {               
                isShooting = false;
            }
        }
    }

    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
    }

    public boolean getIsShooting() {
        return this.isShooting;
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
    }

    public Control cloneForSpatial(Spatial spatial) {
        PlayerShootControl control = new PlayerShootControl(inputManager);
        spatial.addControl(control);
        return control;
    }

    public void onAction(String name, boolean isPressed, float tpf) {
        if (name.equals("PLAYER_Mouse_Left_Click") && isPressed) {
            isShooting = true;
        } else if (name.equals("PLAYER_Mouse_Left_Click") && !isPressed) {
            isShooting = false;
            timeToOverheat = maxTimeToOverheat;
        }
    }
    
    private void initMappings() {
        inputManager.addMapping("PLAYER_Mouse_Left_Click", new MouseButtonTrigger(MouseInput.BUTTON_LEFT),
                new KeyTrigger(KeyInput.KEY_DOWN));
        inputManager.addListener(this, new String[]{"PLAYER_Mouse_Left_Click"});
    }
}
