package com.rv.home.rv.module.ui.main.home.presenter;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.yuyife.okgo.OkGoUtil;

public class HomePresenter extends CommonPresenter {

    /******
     * 打开目标页面
     * @param context
     * @param url
     * @param title
     */
    public void toTarget(Context context, String url, String title, String id) {

        if (!TextUtils.isEmpty(url) && url.contains("login=1")) {
            if (!isLogin(context)) {
                return;
            }
        }
        if (url.startsWith("http")) {
            ComponentName componentName = new ComponentName(context, "com.rv.share.WebViewActivity");
            Intent intent = new Intent();
            intent.setComponent(componentName);
            intent.putExtra("url", url);
            intent.putExtra("title", title);
            intent.putExtra("id", id);
            context.startActivity(intent);
        } else if (url.startsWith("app:")) {
            String target = null;
            String[] params = null;
            if (url.contains("?")) {
                target = url.substring(url.indexOf(":") + 1, url.indexOf("?"));
                String paramsString = url.substring(url.indexOf("?") + 1);
                params = paramsString.split("&");
            } else {
                target = url.substring(url.indexOf(":") + 1);
            }
            if (!TextUtils.isEmpty(target)) {
                ComponentName componentName = new ComponentName(context, target);
                Intent intent = new Intent();
                intent.setComponent(componentName);
                if (params != null && params.length > 0) {
                    for (String param : params) {
                        String[] values = param.split("=");
                        if (values.length == 2) {
                            intent.putExtra(values[0], values[1]);
                        }
                    }
                }
                context.startActivity(intent);
            }
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin(Context context) {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            context.startActivity(LoginRvActivity.getIntent(context, 0));
            return false;
        }
        return true;
    }

}
