package com.bernard.mcqinator.view.activities.fragenActivities;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.bernard.mcqinator.R;
import com.bernard.mcqinator.api.frageable.BlocFrageable;
import com.bernard.mcqinator.api.fragen.BlocFrage;

import java.util.ArrayList;
import java.util.Arrays;

public class BlocFrageActivity extends FrageActivity<BlocFrage> implements View.OnClickListener{

    TextView frage;
    TableLayout tl;
    Button[] buttons;

    @Override
    public void initiate(BlocFrage f) {
        ArrayList<String> replies = new ArrayList<>();
        replies.addAll(Arrays.asList(f.getFalshAntworte()));
        replies.add(f.getRichtigAntwort());
        Log.d("Buttons",Arrays.toString(buttons));
        for (Button button : buttons) {
            int pos = (int) (Math.random() * (double) replies.size());
            button.setText(replies.get(pos));
            replies.remove(pos);
        }
        frage.setText(f.getFrage());
    }

    @Override
    @SuppressWarnings("null")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bloc_frage);

        BlocFrageable.BlocData data = getIntent().getParcelableExtra(QUIZ_DATA);
        int bn = data.blockNumber;

        frage= findViewById(R.id.frageText);
        tl= findViewById(R.id.blocTable);

        TableRow tr = null;
        buttons = new Button[bn];
        TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.WRAP_CONTENT);
        params.weight = 50;
        TableLayout.LayoutParams tparams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
        for(int b = 0;b<bn;b++){
            if(b%2==0) {
                tr = new TableRow(this);
                tr.setLayoutParams(tparams);
            }
            Button butt = new Button(this);
            butt.setLayoutParams(params);

            butt.setOnClickListener(this);
            buttons[b] = butt;
            //noinspection ConstantConditions
            tr.addView(butt);
            if(b%2==1)
                tl.addView(tr);
        }
        if(bn%2==1)
            tl.addView(tr);
    }

    @Override
    public void onClick(View v) {
        BlocFrage.Reply reply = new BlocFrage.Reply(((TextView)v).getText().toString());

        reply(reply);
    }
}
