package com.bokecc.dwlivedemo.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.bokecc.dwlivedemo.BuildConfig;
import com.bokecc.dwlivedemo.Constants;
import com.bokecc.dwlivedemo.DWApplication;
import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.base.BaseActivity;
import com.bokecc.dwlivedemo.popup.CommonDialog;
import com.bokecc.dwlivedemo.popup.PrivacyPolicyDialog;
import com.bokecc.dwlivedemo.utils.PermissionRequestBean;
import com.bokecc.dwlivedemo.utils.StatusBarUtil;
import com.bokecc.livemodule.utils.SPUtil;


/**
 * 首页
 * 观看直播 & 观看回放 & 离线回放 入口选择页
 */
public class PilotActivity extends BaseActivity {

    View mRoot;
    private CheckBox cbSettingDocWebCore;
    private CheckBox cbSettingDocComponent;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 沉浸式
        StatusBarUtil.transparencyBar(this);
        StatusBarUtil.setLightStatusBar(this, true, false);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pilot);
        ((TextView) (findViewById(R.id.about_version_code))).setText(getString(R.string.pilot_version, BuildConfig.VERSION_NAME));

        /**************************************************************************
         *
         *   CC SDK 直播观看核心类：DWLive, 回放观看核心类 DWLiveReplay, 离线回放核心类：DWLiveLocalReplay
         *
         *   使用流程：登录 --> 观看
         *
         *   页面流程：登录页 --> 观看页
         *
         *   流程详解：登录操作的Activity和观看页Activity为两个Activity，监听到登录成功后再跳转到播放页进行观看。
         *
         *   离线回放流程：下载CCR文件 --> 解压文件 --> 调用DWLiveLocalReplay相关方法进行播放
         *
         **************************************************************************/


        // 跳转到直播登录页
        findViewById(R.id.btn_start_live).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PilotActivity.this, LiveLoginActivity.class);
                startActivity(intent);
            }
        });

        // 跳转到回放登录页
        findViewById(R.id.btn_start_replay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PilotActivity.this, ReplayLoginActivity.class);
                startActivity(intent);
            }
        });

        // 跳转到离线回放列表页
        findViewById(R.id.btn_start_local_replay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(PilotActivity.this, DownloadListActivity.class);
                //检查存储权限-不必须
                PermissionRequestBean permissionRequestBean = new PermissionRequestBean(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE});
                permissionRequestBean.request(PilotActivity.this, new PermissionRequestBean.PermissionCallback() {
                    @Override
                    public void onResult(boolean success) {
                        if (success){
                            startActivity(intent);
                        }else {
                            toastOnUiThread("权限被您拒绝，请前往权限设置中开启存储权限后使用离线回放功能");
                        }
                    }
                });
            }
        });

        findViewById(R.id.btn_start_vertical_live).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PilotActivity.this,VerticalLiveLoginActivity.class);
                startActivity(intent);
            }
        });

        mRoot = getWindow().getDecorView().findViewById(android.R.id.content);
        if (!DWApplication.getInstance().getPrivacy()) {
            mRoot.post(new Runnable() {
                @Override
                public void run() {
                    showPrivacyPopup();
                }
            });
        }

        //配置
        cbSettingDocWebCore = findViewById(R.id.cb_setting_doc_web_core);
        cbSettingDocComponent = findViewById(R.id.cb_setting_doc_component);

        //读取配置，测试包可见，仅用于测试使用
        initSetting();

        //初始化协议
        initAgreement();

        //初始化Listener
        initListener();


    }

    private void initListener() {
        cbSettingDocWebCore.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPUtil.getInstance().put(Constants.SP_WEB_CORE_KEY,isChecked);
                toastOnUiThread(isChecked?"重启APP以启用x5内核":"重启APP以启用原生内核");
            }
        });
        cbSettingDocComponent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPUtil.getInstance().put(Constants.SP_DOC_COMPONENT_KEY,isChecked);
                toastOnUiThread(isChecked?"使用docsdk，立即生效":"使用内置文档模块，立即生效");
            }
        });
    }

    private void initAgreement() {
        TextView textView = findViewById(R.id.about_privacy);
        textView.setClickable(true);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        String text = "登录即代表你同意《服务协议》和《隐私协议》";
        int start1 = text.indexOf("《");
        int end1 = text.indexOf("》");
        int start2 = text.indexOf("《", end1);
        int end2 = text.indexOf("》", end1 + 1);
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PilotActivity.this, PolicyActivity.class);
                intent.putExtra("url", "https://admin.bokecc.com/agreement.bo");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        }, start1 + 1, end1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff842f")), start1 + 1, end1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PilotActivity.this, PolicyActivity.class);
                intent.putExtra("url", "https://admin.bokecc.com/privacy.bo");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        }, start2 + 1, end2 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff842f")), start2 + 1, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        textView.setText(spannableString);
    }

    private void initSetting() {
        if (BuildConfig.DEBUG){
            cbSettingDocWebCore.setVisibility(View.VISIBLE);
            cbSettingDocComponent.setVisibility(View.VISIBLE);
        }else {
            cbSettingDocWebCore.setVisibility(View.GONE);
            cbSettingDocComponent.setVisibility(View.GONE);
        }
        boolean isUseX5 = SPUtil.getInstance().getBoolean(Constants.SP_WEB_CORE_KEY,true);
        cbSettingDocWebCore.setChecked(isUseX5);
        boolean isDocSdk = SPUtil.getInstance().getBoolean(Constants.SP_DOC_COMPONENT_KEY,true);
        cbSettingDocComponent.setChecked(isDocSdk);

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private PrivacyPolicyDialog privacyPolicyDialog;
    private CommonDialog permissionDialog;

    private void showPrivacyPopup() {
        if (privacyPolicyDialog == null) {
            privacyPolicyDialog = new PrivacyPolicyDialog(this).setOnClickAgree(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DWApplication.getInstance().setPrivacy(true);
                    privacyPolicyDialog.dismiss();
                    DWApplication.getInstance().init(getApplication());
                    //显示权限弹窗
                    showPermissionNotifyPopup();
                }
            }).setOnClickIgnore(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    privacyPolicyDialog.dismiss();
                    finish();
                }
            });

            String policy = "欢迎使用HD云观众APP，我们非常重视您的个人信息和隐私保护，为了更好的保护您的个人利益，在您使用我们产品前，请仔细阅读《服务协议》和《隐私协议》的所有条款。";
            int startIndex1 = policy.indexOf("《");
            int endIndex1 = policy.indexOf("》");
            SpannableString spannableString = new SpannableString(policy);
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(PilotActivity.this, PolicyActivity.class);
                    intent.putExtra("url", "https://admin.bokecc.com/agreement.bo");
                    startActivity(intent);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }
            }, startIndex1 + 1, endIndex1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff842f")), startIndex1 + 1, endIndex1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            int startIndex2 = policy.indexOf("《", endIndex1);
            int endIndex2 = policy.indexOf("》", endIndex1 + 1);
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(PilotActivity.this, PolicyActivity.class);
                    intent.putExtra("url", "https://admin.bokecc.com/privacy.bo");
                    startActivity(intent);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }
            }, startIndex2 + 1, endIndex2 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff842f")), startIndex2 + 1, endIndex2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            privacyPolicyDialog.setPolicyTipString(spannableString);
        }
        privacyPolicyDialog.showBottom();
    }

    private void showPermissionNotifyPopup() {
        if (permissionDialog == null) {
            permissionDialog = new CommonDialog(this).setOnClickAgree(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    permissionDialog.dismiss();
                }
            }).setOnClickIgnore(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });

            String policy = "HD云观众APP在运行过程中将在适当时机向您申请以下权限：\n1. 存储权限：用于离线日志存储以及离线回放存储\n2. 相机权限：用于登录扫码以及连麦功能使用\n3. 麦克风权限：用于连麦功能使用\n为保证功能正常运行，请允许相关权限。";
            permissionDialog.setContent(policy);
            permissionDialog.setHideCancelButton();
            permissionDialog.setAgreeButtonText("我已知晓");
        }
        permissionDialog.showCenter();
    }


    @Override
    public void onBackPressed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition();
        } else {
            super.onBackPressed();
        }
    }


}
