package de.frajul.endlessroll.views;

import android.view.View;
import android.widget.TextView;

import java.util.concurrent.atomic.AtomicBoolean;

import de.frajul.endlessroll.R;
import de.frajul.endlessroll.main.GameActivity;
import de.frajul.endlessroll.main.GameLog;
import de.frajul.endlessroll.main.game.Game;
import de.frajul.endlessroll.sounds.SoundStream;

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

    private Game game;
    private GameActivity gameActivity;
    private TextView textView;
    private SoundStream soundStream;

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

    public Countdown(Game game, GameActivity gameActivity, TextView textView) {
        this.game = game;
        this.gameActivity = gameActivity;
        this.textView = textView;
        this.textView.setTypeface(gameActivity.getTypeface());
        running = new AtomicBoolean(false);
    }

    public void update(float delta) {
        if (running.get()) {
            time += delta;
            if (time >= 1000 && currentSeconds == 0)
                onNextSecondInUiThread(1);
            if (time >= 2000 && currentSeconds == 1)
                onNextSecondInUiThread(2);
            if (time >= 3000 && currentSeconds == 2) {
                gameActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setVisibility(View.GONE);
                    }
                });
                running.set(false);
                game.countdownFinished();
            }
        }
    }

    public void start() {
        reset();
        running.set(true);
        textView.setVisibility(View.VISIBLE);
        soundStream = gameActivity.getSoundManager()
                .playSound(gameActivity.getSoundManager().countdownSound);
    }

    public void stop() {
        textView.setVisibility(View.GONE);
        running.set(false);
        if (soundStream != null)
            gameActivity.getSoundManager().stopSound(soundStream);
    }

    private void reset() {
        time = 0;
        onNextSecondInUiThread(0);
    }

    private void onNextSecondInUiThread(final int second) {
        gameActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                currentSeconds = second;
                textView.setText((3 - second) + "");
                int color = R.color.countdown1;
                if (second == 1)
                    color = R.color.countdown2;
                else if (second == 2)
                    color = R.color.countdown3;
                textView.setTextColor(game.getContext().getResources().getColor(color));
            }
        });
    }

}
