package com.common.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.widget.CheckBox;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import tech.starwin.LibConfig;
import tech.starwin.R;

import com.common.base.BaseActivity;

import tech.starwin.constants.ActionEnum;
import tech.starwin.impl.OnEventClickListener;
import tech.starwin.impl.OnNoShakeClickListener;
import tech.starwin.network.Gateway;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.TrackEventHelper;
import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.ui_utils.DialogFactory;
import tech.starwin.utils.ui_utils.UIHelper;

import com.common.toolbox.tracker.TrackEvent;
import com.common.widget.TopBar;

import java.io.Serializable;

/**
 * Created by SiKang on 2018/11/19.
 * 注册协议及隐私政策
 */
public class AgreementPolicyActivity extends BaseActivity {
    public enum Type implements Serializable {
        AGREEMENT_POLICY,
        AGREEMENT_KSP,
        AGREEMENT_HOOK
    }


    Type agreementType;

    public static void startForResult(FragmentActivity activity, Type type, int requestCode, EasyActivityResult.OnResultListener listener) {
        Intent intent = new Intent(activity, AgreementPolicyActivity.class);
        if (type != null) {
            intent.putExtra("agreementType", type);
        }
        new EasyActivityResult(activity).startForResult(intent, requestCode, listener);
    }

    public static void startForResult(FragmentActivity activity, int requestCode, EasyActivityResult.OnResultListener listener) {
        Intent intent = new Intent(activity, AgreementPolicyActivity.class);
        new EasyActivityResult(activity).startForResult(intent, requestCode, listener);
    }

    CheckBox mCheckBox;
    WebView webView;

    @Override
    public int bindLayout() {
        return R.layout.activity_policy;
    }

    @Override
    protected void initTopBar(TopBar topBar) {
        topBar.toolBar().setTitleGravity(Gravity.CENTER);
        topBar.toolBar().setTitle(R.string.login_statement_title);
    }

    @Override
    public void initView() {
        if (getIntent().getSerializableExtra("agreementType") != null) {
            agreementType = (Type) getIntent().getSerializableExtra("agreementType");
        }
        EventBus.getDefault().register(this);
        mCheckBox = findViewById(R.id.activity_policy_checkbox);
        webView = findViewById(R.id.activity_policy_webview);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不加载缓存
        WebStorage.getInstance().deleteAllData();//主动清除数据

        UIHelper.bindClickListener(getContentView(), new OnNoShakeClickListener() {
            @Override
            public void onEventClick(View v) {
                if (v.getId() == R.id.activity_policy_ok_btn) {
                    if (mCheckBox.isChecked()) {
                        if (agreementType == null) {
                            PreferencesManager.get().setPolicyStatus(true);
                            TrackEventHelper.logEvent(TrackEvent.Click.AGREE_PRIVACY);
                            setResult(RESULT_OK);
                            finish();
                            return;
                        }
                        switch (agreementType) {
                            case AGREEMENT_POLICY:
                                PreferencesManager.get().setPolicyStatus(true);
                                AgreementPolicyActivity.startForResult(AgreementPolicyActivity.this, Type.AGREEMENT_KSP, 0, (requestCode, resultCode, data) -> {
                                    if (resultCode == RESULT_OK) {
                                        setResult(Activity.RESULT_OK);
                                        TrackEventHelper.logEvent(TrackEvent.Click.AGREE_PRIVACY);
                                    }
                                    finish();
                                });
                                break;
                            case AGREEMENT_KSP:
                                PreferencesManager.get().setPolicyKSPStatus(true);
                                setResult(RESULT_OK);
                                finish();
                                break;
                            case AGREEMENT_HOOK:
                                PreferencesManager.get().setPolicyStatus(true);
                                setResult(RESULT_OK);
                                finish();
                                break;
                        }
                    } else {
                        DialogFactory.showMessageDialog(AgreementPolicyActivity.this, getString(R.string.check_the_checkbox));
                    }

                }
            }
        }, R.id.activity_policy_ok_btn);

        String policyUrl;
        if (agreementType != Type.AGREEMENT_KSP) {
            policyUrl = Gateway.getAgreementPolicyUrl();
        } else {
            policyUrl = Gateway.getKSPUrl();
        }

        //假协议
        if (agreementType == Type.AGREEMENT_HOOK) {
            webView.loadUrl("file:///android_asset/web/privacy.html?name=" + LibConfig.APP_NAME.replace(" ","%20"));
            return;
        }

        if (!TextUtils.isEmpty(policyUrl)) {
            webView.loadUrl(policyUrl);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveLibAction(String actionEnum) {
        switch (actionEnum) {
            case ActionEnum.GATEWAY_UPDATED:
                webView.loadUrl(Gateway.getAgreementPolicyUrl());
                break;
        }
    }


    public void loadUrlWithParams(WebView webView, String url) {
        String[] urls = url.split("\\?");
        if (urls.length > 1) {
            String[] params = urls[1].split("&");

        }
    }

    @Override
    public void onHttpSuccess(String action, Object result) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
