package com.iq.intelligence.study;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

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

public class LevelsPageActivity extends AppCompatActivity {


    SharedPreferences prefs;
    private RecyclerView recyclerView;
    private List<LevelsBean> list;
    private GameLevelsAdapter levelsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_grades);

        recyclerView = findViewById(R.id.levels_list);
        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        prefs = getSharedPreferences(PrescribedValue.PRE_FILE, Context.MODE_PRIVATE);


        initList();

    }

    private void initList() {
        SharedPreferences.Editor edit = prefs.edit();
        edit.putBoolean(String.format(getString(R.string.LevelValue), String.valueOf(1)), true);
        edit.apply();
        list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            LevelsBean levelsBean;
            int levels = i + 1;
            String format = String.format(getString(R.string.LevelValue), String.valueOf(levels));
            boolean aBoolean = prefs.getBoolean(format, false);
            levelsBean = new LevelsBean(aBoolean, levels);
            list.add(levelsBean);
        }
        levelsAdapter = new GameLevelsAdapter(this, list);
        recyclerView.setAdapter(levelsAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 5));

    }


    @Override
    protected void onStart() {
        super.onStart();

        for (LevelsBean bean : list) {
            int index = list.indexOf(bean);
            String format = String.format(getString(R.string.LevelValue), String.valueOf(bean.getLevels()));
            boolean aBoolean = prefs.getBoolean(format, false);
            if (aBoolean) {
                bean.setUnlock(aBoolean);
                levelsAdapter.updateUnlock(index);
            }
        }


    }
}