package de.frajul.endlessroll.views;

import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import de.frajul.endlessroll.R;
import de.frajul.endlessroll.levels.Level;
import de.frajul.endlessroll.main.GameActivity;

/**
 * Created by Julian on 23.04.2016.
 */
public class LevelButton implements View.OnClickListener {

    private GameActivity gameActivity;
    private LevelButtonOnClickListener clickListener;
    private Level level;

    private View layout;
    private TextView text;
    private ImageView star1;
    private ImageView star2;
    private ImageView star3;
    private ImageView energy;
    private ImageView lockImage;

    public LevelButton(GameActivity gameActivity, LevelButtonOnClickListener clickListener, @LayoutRes int layoutId) {
        this.gameActivity = gameActivity;
        this.clickListener = clickListener;
        LayoutInflater inflater = LayoutInflater.from(gameActivity);
        layout = inflater.inflate(layoutId, null);
        layout.setOnClickListener(this);
        findViews(layout);
    }

    private void findViews(View layout) {
        text = (TextView) layout.findViewById(R.id.levelbutton_textview);
        text.setTypeface(gameActivity.getTypeface());
        star1 = (ImageView) layout.findViewById(R.id.levelbutton_star1);
        star2 = (ImageView) layout.findViewById(R.id.levelbutton_star2);
        star3 = (ImageView) layout.findViewById(R.id.levelbutton_star3);
        energy = (ImageView) layout.findViewById(R.id.levelbutton_energy);
        lockImage = (ImageView) layout.findViewById(R.id.levelbutton_lock);
    }

    public void init(Level level) {
        this.level = level;
        setLockVisible(level.isLocked());
        text.setText(gameActivity.getString(R.string.level_button_format_d, level.getId()));
        showCollectedCurrency(level.getCollectedStars(), level.isEnergyCollected());
    }

    private void setLockVisible(boolean locked) {
        int visibility = locked ? View.VISIBLE : View.GONE;
        lockImage.setVisibility(visibility);
    }

    private void showCollectedCurrency(boolean[] stars, boolean energy) {
        if (stars[0])
            this.star1.setImageResource(R.drawable.currency_star);
        if (stars[1])
            this.star2.setImageResource(R.drawable.currency_star);
        if (stars[2])
            this.star3.setImageResource(R.drawable.currency_star);
        if (energy)
            this.energy.setImageResource(R.drawable.currency_energy);
    }

    public Level getLevel() {
        return level;
    }

    public View getView(){
        return layout;
    }

    @Override
    public void onClick(View v) {
        clickListener.onClick(this);
    }
}
