package com.fun.funnyprank.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fun.funnyprank.FunnyPrankSkin;
import com.fun.funnyprank.activity.SettingActivity;
import com.fun.funnyprank.adapter.ThumAdapter;
import com.fun.funnyprank.data.LikeData;
import com.fun.funnyprank.data.MydataBase;
import com.fun.funnyprank.databinding.FragmentMainBinding;
import com.fun.funnyprank.tools.SpaceItem;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainFragment extends Fragment {

    FragmentMainBinding bind;
    private ThumAdapter thumAdapter;
    private SpaceItem spaceItem = new SpaceItem(12, 20, 12);

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        bind = FragmentMainBinding.inflate(inflater, container, false);

        initData();

        bind.mainSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireContext(), SettingActivity.class);
                startActivity(intent);
            }
        });

        return bind.getRoot();
    }

    private void initData() {
        MydataBase.getInstance().likeDao().livegetAll().observe(getViewLifecycleOwner(), new Observer<List<LikeData>>() {
            @Override
            public void onChanged(List<LikeData> list) {
                initView(chekData(list));

            }
        });
    }

    private void initView(List<LikeData> maindata) {
        thumAdapter = new ThumAdapter(requireActivity(), maindata);
        bind.marinRv.setAdapter(thumAdapter);
        bind.marinRv.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        bind.marinRv.addItemDecoration(spaceItem);
    }

    private static List<LikeData> chekData(List<LikeData> data) {

        List<LikeData> main = new ArrayList<>();
        Set<String> name = new HashSet<>();
        for (LikeData mydata : data) {
            if (!name.contains(mydata.getCategoryname())) {
                main.add(mydata);
                name.add(mydata.getCategoryname());
            }
        }
        return main;
    }

}