package com.amm.dynamicbuttons;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import static java.security.AccessController.getContext;

public class MainActivity extends AppCompatActivity {

    static int initialButtons = 2;

    Button btnAdd, btnRemove;
    TextView tvCounter;

    private int numButtons=initialButtons;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnRemove = (Button) findViewById(R.id.btnRemove);
        tvCounter = (TextView) findViewById(R.id.tvCounter);

        LinearLayout llvBotonera = (LinearLayout) findViewById(R.id.llvBotonera);
        //Creamos los parametros (with y hight)
        LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        for (int i=1; i<=initialButtons; i++){
            Button button = new Button(getApplicationContext());
            button.setLayoutParams(lparams);
            button.setTag("Button " + Integer.toString(i));
            button.setText("Button " + Integer.toString(i));
            button.setOnClickListener(new ButtonsOnClickListener(getApplicationContext()));
            llvBotonera.addView(button);
        }

        tvCounter.setText(Integer.toString(numButtons));

        btnAdd.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                numButtons++;
                String tag = "Button " + Integer.toString(numButtons);
                Button button = new Button(getApplicationContext());
                button.setLayoutParams(lparams);
                button.setTag(tag);
                button.setText(tag);
                button.setOnClickListener(new ButtonsOnClickListener(getApplicationContext()));
                llvBotonera.addView(button);
                tvCounter.setText(Integer.toString(numButtons));
            }
        });

        btnRemove.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if (numButtons>0) {
                    String tag = "Button " + Integer.toString(numButtons);
                    Button button = (Button) llvBotonera.findViewWithTag(tag);
                    llvBotonera.removeView(button);
                    numButtons--;
                    tvCounter.setText(Integer.toString(numButtons));
                }
            }
        });

    }


}