package com.huawei.hwmdemo.view.sdkconfig.menu;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.constant.ConfigConstant;
import com.huawei.hwmdemo.delegate.DelegateHolder;
import com.huawei.hwmdemo.model.FeaturePage;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.utils.PreferencesUtil;
import com.huawei.hwmdemo.view.BaseActivity;

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

/**
 * 功能描述:demo自定义移除菜单项便于测试自定义菜单的功能
 *
 * @author l00621708
 * @since 2022-05-25
 */
public class MenuConfigActivity extends BaseActivity {

    private List<MenuConfigFragment> pages;
    private TabLayoutMediator tvmPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_menu_config);
        TabLayout tlType = findViewById(R.id.tl_type);
        initData();
        ViewPager2 vpPage = findViewById(R.id.vp_page);
        vpPage.setAdapter(new FragmentStateAdapter(this) {
            @Override
            public Fragment createFragment(int position) {
                return pages.get(position);
            }

            @Override
            public int getItemCount() {
                return pages.size();
            }
        });

        tvmPage = new TabLayoutMediator(tlType, vpPage, false, true,
                (tab, position) -> tab.setText(pages.get(position).getName()));
        tvmPage.attach();
    }

    private void initData() {
        pages = new ArrayList<>();
        for (FeaturePage menuConfigPage : DelegateHolder.getHwmUiDelegate().getMenuConfigPages()) {
            if (menuConfigPage.getFragment() instanceof MenuConfigFragment) {
                pages.add((MenuConfigFragment) menuConfigPage.getFragment());
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        PreferencesUtil.setStringPreferences(DemoUtil.getApplication(), ConfigConstant.KEY_DISABLE_MENU_CONFIG, new Gson().toJson(DemoUtil.getDisabledMenuConfig()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tvmPage.detach();
    }
}
