package de.frajul.endlessroll.views;

import android.graphics.Typeface;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import de.frajul.endlessroll.R;
import de.frajul.endlessroll.main.game.Game;

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

    private Game game;
    private AnimationSet animations;
    private TextView textView;

    private boolean firstHalfRepeated = true;
    private int repeatCount = 0;

    public Countdown(Game game, Typeface typeface, TextView textView) {
        this.game = game;
        this.textView = textView;
        this.textView.setTypeface(typeface);
        animations = (AnimationSet) AnimationUtils.loadAnimation(game.getContext(), R.anim.countdown);
        for (Animation animation : animations.getAnimations())
            animation.setAnimationListener(this);
    }

    public void start() {
        reset();
        textView.startAnimation(animations);
    }

    public void stop() {
        textView.clearAnimation();
    }

    private void reset() {
        repeatCount = 0;
        textView.setText("3");
        textView.setTextColor(game.getContext().getResources().getColor(R.color.countdown3));
    }

    @Override
    public void onAnimationStart(Animation animation) {
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        game.countdownFinished();
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        if (!firstHalfRepeated)
            repeatCount++;
        firstHalfRepeated = !firstHalfRepeated;
        textView.setText((3 - repeatCount) + "");
        if (repeatCount == 1) {
            textView.setTextColor(game.getContext().getResources().getColor(R.color.countdown2));
        } else if (repeatCount == 2) {
            textView.setTextColor(game.getContext().getResources().getColor(R.color.countdown1));
        }
    }
}
