package com.huawei.hwmdemo.view.scheme;

import android.util.Log;

import androidx.fragment.app.DialogFragment;

import com.huawei.hwmdemo.model.ApiPageModel;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.base.BaseListFragment;

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

public class SchemeListFragment extends BaseListFragment {
    // 重要：后续添加项目必须从后面插入，不能前面插入
    private List<String> titles = Arrays.asList("启动","登录","入会","带登录nonce入会","nonce启动应用登录",
        "无效nonce启动应用登录", "启动并打开控制器页面");
    private List<Class> fragments = Arrays.asList(
            null,
            LinkLoginFragment.class,
            LinkJoinFragment.class,
            LoginedLinkJoinFragment.class,
            LinkAppWithNonceFragment.class,
            null,
            null);

    @Override
    public List<ApiPageModel> getItems() {
        List<ApiPageModel> items = new ArrayList<>();
        for (int i = 0; i < titles.size(); i++) {
            ApiPageModel model = new ApiPageModel();
            model.name = titles.get(i);
            model.page = fragments.get(i);
            items.add(model);
        }
        return items;
    }

    @Override
    public void handleItemClick(int position, ApiPageModel data) {
        if (position == 0) {
            start();
        } else if (position == 5) {
            doNonceLinkApp("fake-nonce");
        } else if (position == 6) {
            startAndRouteToController();
        } else {
            if (data.page != null) {
                try {
                    DialogFragment f = (DialogFragment) data.page.newInstance();
                    if (!f.isAdded()) {
                        f.show(getActivity().getSupportFragmentManager(), null);
                    }
                } catch (IllegalAccessException | java.lang.InstantiationException e) {
                    Log.e("SchemeListFragment", e.getMessage());
                }
            } else {
                Log.e("SchemeListFragment", "not found page");

            }
        }
    }

    private void startAndRouteToController() {
        String startUrl = "cloudlink://welinksoftclient/h5page?page=controller";
        DemoUtil.openCloudLinkWithURL(getContext(),startUrl);
    }

    private void start() {
        String startUrl = "cloudlink://welinksoftclient/h5page?page=launch";
        DemoUtil.openCloudLinkWithURL(getContext(),startUrl);
    }

    private void doNonceLinkApp(String nonce) {
        String startUrl = "cloudlink://welinksoftclient/h5page?page=launch&nonce=" + nonce;
        DemoUtil.openCloudLinkWithURL(getContext(),startUrl);
    }
}
