package de.frajul.endlessroll.entities.guis;

import java.util.concurrent.atomic.AtomicBoolean;

import de.frajul.endlessroll.data.Vector;
import de.frajul.endlessroll.entities.Entity;
import de.frajul.endlessroll.entities.textures.Texture;
import de.frajul.endlessroll.entities.textures.TexturePack;
import de.frajul.endlessroll.main.game.Game;
import de.frajul.endlessroll.sounds.SoundManager;
import de.frajul.endlessroll.sounds.SoundStream;

/**
 * Created by Julian on 31.07.2016.
 */
public class Countdown extends Gui {

    private Game game;
    private SoundManager soundManager;
    private SoundStream soundStream;
    private Texture texture3;
    private Texture texture2;
    private Texture texture1;

    private AtomicBoolean running;
    private int currentSeconds = 0;
    private float time = 0;

    public Countdown(Game game, SoundManager soundManager, TexturePack texturePack) {
        super(texturePack.countdown3, new Vector(), 0.8f, 0.8f);
        this.game = game;
        this.soundManager = soundManager;
        this.texture3 = texturePack.countdown1;
        this.texture2 = texturePack.countdown2;
        this.texture1 = texturePack.countdown3;
        running = new AtomicBoolean(false);
    }

    public void update(float delta) {
        if (running.get()) {
            time += delta;
            if (time >= 1000 && currentSeconds == 0) {
                currentSeconds = 1;
                onNextSecondThread(currentSeconds, true);

            }
            if (time >= 2000 && currentSeconds == 1) {
                currentSeconds = 2;
                onNextSecondThread(currentSeconds, true);
            }
            if (time >= 3000 && currentSeconds == 2) {
                currentSeconds = 3;
                running.set(false);
                game.countdownFinished();
            }
        }
    }

    public void start() {
        reset();
        running.set(true);
        soundStream = soundManager.playSound(soundManager.countdownSoundSingle);
    }

    public void stop() {
        running.set(false);
        if (soundStream != null)
            soundManager.stopSound(soundStream);
    }

    private void reset() {
        time = 0;
        currentSeconds = 0;
        onNextSecondThread(0, false);
    }

    private void onNextSecondThread(final int second, final boolean playSound) {
        if (playSound) {
            if (second == 2)
                soundStream = soundManager.playSound(soundManager.countdownSoundLast);
            else
                soundStream = soundManager.playSound(soundManager.countdownSoundSingle);
        }
        super.setTexture(texture1);
        if (second == 1)
            super.setTexture(texture2);
        else if (second == 2)
            super.setTexture(texture3);
    }

    @Override
    public boolean isVisible() {
        return running.get();
    }
}
