package com.yidianling.user.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.CustomInterface;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.InitResult;
import com.yidianling.user.R;

@Route(path = "/user/aliAuthDemo")
public class AliAuthDemoActivity extends Activity {
    private PhoneNumberAuthHelper mAlicomAuthHelper;
    private TokenResultListener mTokenListener;
    private Button mVaildBtn, mLoginBtn;
    private TextView mRetTV;
    private InitResult mAutCheckResult;
    private SparseArray<PermissionCallback> mPerMissionCallbackCache;
    private int mCurrentPermissionRequestCode = 0;
    private ProgressDialog mProgressDialog;
    private String token;
    private TextView mDynamicView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_activity_ali_auth_demo);
        mVaildBtn = (Button) findViewById(R.id.vaild_button);
        mLoginBtn = (Button) findViewById(R.id.login_button);
        mRetTV = (TextView) findViewById(R.id.operator_name_tv);
        init();
    }

    private void initDynamicView() {
        mDynamicView = new TextView(getApplicationContext());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        layoutParams.setMargins(0, dp2px(this, 450), 0, 0);
        mDynamicView.setText("-----  自定义view  -----");
        mDynamicView.setTextColor(0xff999999);
        mDynamicView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.0F);
        mDynamicView.setLayoutParams(layoutParams);
    }

    public static int dp2px(Context context, float dipValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dipValue * scale + 0.5f);
        } catch (Exception e) {
            return (int) dipValue;
        }
    }

    private void init() {
        /*
         *   1.init get token callback Listener
         */
        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(final String ret) {
                mDynamicView = null;
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *   setText just show the result for get token。
                         *   use ret to verfiy number。
                         */
                        hideLoadingDialog();
                        token = ret;
                        mRetTV.setText("成功:\n" + ret);
                        mAlicomAuthHelper.quitAuthActivity();
                    }
                });
            }

            @Override
            public void onTokenFailed(final String ret) {
                mDynamicView = null;
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *  setText just show the result for get token
                         *  do something when getToken failed, such as use sms verify code.
                         */
                        hideLoadingDialog();
                        mRetTV.setText("失败:\n" + ret);
                        mAlicomAuthHelper.quitAuthActivity();
                    }
                });
            }
        };

        /*
         *   2.init AlicomAuthHelper with tokenListener
         */
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);

        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
//        if (isApkInDebug(this)) {
        mAlicomAuthHelper.setDebugMode(true);
//        }

        /*
         *   4.ask permission from user, this step is not necessary
         *   just do when your app is needed
         */
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionCallback() {
                @Override
                public void onPermissionGranted(boolean isRequestUser) {
                    /*
                     *   5.sdk init
                     */
                    mAutCheckResult = mAlicomAuthHelper.checkAuthEnvEnable();
                }

                @Override
                public void onPermissionDenied(boolean isRequestUser) {
                    Toast.makeText(AliAuthDemoActivity.this, "请允许相关权限", Toast.LENGTH_LONG).show();
                }
            });
        } else {
            /*
             *   5.sdk init
             */
            mAutCheckResult = mAlicomAuthHelper.checkAuthEnvEnable();
        }

        mVaildBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog("正在请求认证token");
                mAlicomAuthHelper.getAuthToken(5000);
            }
        });

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDynamicView();
                mAlicomAuthHelper.addAuthRegistViewConfig("my_tv", new AuthRegisterViewConfig.Builder()
                        .setView(mDynamicView)
                        .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                        .setCustomInterface(new CustomInterface() {
                            @Override
                            public void onClick(Context context) {
                                Toast.makeText(context, "点击自定义控件", Toast.LENGTH_LONG).show();
                            }
                        }).build());
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(5000);
            }
        });

        /*
         *   7.user sdk init result to do someting
         *   this step is also not necessary
         *   if you do this step, user experience maybe better
         */
        if (mAutCheckResult != null) {
            //judge the phone condition can use 4g auth
            if (!mAutCheckResult.isCan4GAuth()) {
                mVaildBtn.setClickable(false);
                mRetTV.setText("请开启移动网络后重试！");
            }
        }

        /*
         *   8.config authorization page ui to adapte app ui theme
         */
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("自定义协议", "https://www.aliyun.com/product/dypns")
                .setLogoImgPath("ic_launcher")
                .setPrivacyState(true)
                .setCheckboxHidden(true)
                .create());

        mAlicomAuthHelper.preLogin(5, new PreLoginResultListener() {
            @Override
            public void onTokenSuccess(final String s) {
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *  推荐在登录页初始化的时候调用
                         *  如果没有合适的调用时机
                         *  不调用此接口也没关系
                         *  千万不要APP冷启动初始化就调用！！！！
                         *  最好判断用户是否登录，若已登录不要使用此接口！！！！
                         */
                        mRetTV.setText("预取号成功:" + s);
                    }
                });
            }

            @Override
            public void onTokenFailed(final String s, final String s1) {
                /*
                 *  预取号调用失败
                 *  不用太关注，还是可以直接在用户点击"登录"时，调用getLoginToken
                 */
                mRetTV.setText("预取号失败:" + s + s1);
            }
        });

    }

    @Override
    protected void onDestroy() {
        /*
         *   8.remember on destory
         */
        mAlicomAuthHelper.onDestroy();
        super.onDestroy();
    }

    /*
     *  Dynamic request application permissions
     */
    protected void requestPermission(String[] permissions, PermissionCallback callback) {
        int result = PackageManager.PERMISSION_GRANTED;
        for (String s : permissions) {
            if (ContextCompat.checkSelfPermission(this, s) != PackageManager.PERMISSION_GRANTED)
                result = PackageManager.PERMISSION_DENIED;
        }

        if (result == PackageManager.PERMISSION_GRANTED && callback != null) {
            callback.onPermissionGranted(false);
        } else {
            if (Build.VERSION.SDK_INT >= 23) {
                if (mPerMissionCallbackCache == null)
                    mPerMissionCallbackCache = new SparseArray<PermissionCallback>();
                mPerMissionCallbackCache.put(mCurrentPermissionRequestCode, callback);
                requestPermissions(permissions, mCurrentPermissionRequestCode++);
            } else if (callback != null) {
                callback.onPermissionDenied(false);
            }
        }
    }

    public interface PermissionCallback {
        void onPermissionGranted(boolean isRequestUser);

        void onPermissionDenied(boolean isRequestUser);
    }

    public boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null)
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
    }


}

