package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private final static int INITIAL_SIZE = 20;
    // TODO: Uncomment this to check it doesn't crash if initially we insert 30 span items, because
    // mData is resized to a bigger size and the last full span index doesn't reach the bounds.
    //private final static int INITIAL_SIZE = 30;

    private static final ArrayList<Integer> FULL_SPAN_ITEMS = new ArrayList();
    static {
        FULL_SPAN_ITEMS.add(0);
        FULL_SPAN_ITEMS.add(13);
        FULL_SPAN_ITEMS.add(16);
        FULL_SPAN_ITEMS.add(17);
        FULL_SPAN_ITEMS.add(18);
        FULL_SPAN_ITEMS.add(19);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RecyclerView recyclerView = findViewById(R.id.rvTest);
        final TestAdapter adapter = new TestAdapter(getInitialData(INITIAL_SIZE));

        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(layoutManager);

        final Button clickToCrash = findViewById(R.id.btnClickToCrash);
        clickToCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 14; i < 32; i++) {
                    adapter.addItemAt(i, false);
                }
            }
        });
    }

    private List<Boolean> getInitialData(int size) {
        final List<Boolean> data = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            data.add(FULL_SPAN_ITEMS.contains(i));
        }

        return data;
    }
}