/*
 * Copyright (C) 2013 Darth Affe <http://wyrez.org> and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.wyrez.shootingstars.controls;

import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import org.wyrez.shootingstars.helper.ColorHelper;
import org.wyrez.shootingstars.helper.UserDataKeys;

/**
 *
 * @author Snowsun
 */
public class StarPointControl extends BaseControl {

    private static final float MAX_POINTS = 100f;
    private static final float HIT_TIMER = 5f;
    /**/
    private float points;
    private Spatial player;
    private ColorRGBA color;
    private Material material;
    private float timer;
    private boolean isHitted = false;

    public StarPointControl(Spatial player, float value) {
        this.player = player;
        this.points = (int) Math.round(MAX_POINTS * value);
        this.timer = HIT_TIMER;
        this.color = ColorHelper.calcColor(points / MAX_POINTS);
    }

    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
        this.material = ((Geometry) spatial).getMaterial();
        material.setColor("Color", color);
    }

    @Override
    protected void controlUpdate(float tpf) {
        if ((Boolean) spatial.getUserData(UserDataKeys.HITTED) && !isHitted) {
            player.setUserData(UserDataKeys.POINTS, (Integer) (player.getUserData(UserDataKeys.POINTS))
                    + (int) Math.round(points));
            isHitted = true;
        } else if (timer <= 0f) {
            if (points > 1f) {
                points -= 2f * tpf;
                color = ColorHelper.calcColor(points / MAX_POINTS);
            } else if (points <= 1f) {
                points = 1f;
                color = ColorHelper.calcColor(points / MAX_POINTS);
                spatial.setUserData(UserDataKeys.HITTED, true);
            }
            material.setColor("Color", color);
        } else {
            timer -= tpf;
        }
    }

    public ColorRGBA getColor() {
        return color;
    }

    public Control cloneForSpatial(Spatial spatial) {
        StarPointControl control = new StarPointControl(player, (float) points);
        spatial.addControl(control);
        return control;
    }
}
