package com.xxfc.rv.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.rv.component.utils.AppCookie;
import com.rv.component.utils.Cookie;
import com.rv.im.AppConfig;
import com.rv.im.bean.ImConfigBean;
import com.xxfc.rv.GuideActivity;
import com.xxfc.rv.MainActivity;
import com.xxfc.rv.PrivacySecondTipsDialog;
import com.xxfc.rv.PrivacyThirdTipsDialog;
import com.xxfc.rv.PrivacyFirstTipsDialog;
import com.yuyife.okgo.OkGoUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class WelcomePresenter extends CommonPresenter {

    public static final int CODE_REQUEST_POISITION = 1000;

    private Disposable mDisposable = null;

    private Activity mActivity;

    private PrivacyFirstTipsDialog privacyfirstTipsDialog;

    private PrivacySecondTipsDialog privacySecondTipsDialog;

    private PrivacyThirdTipsDialog privacyThirdTipsDialog;

    /*****
     *  同意隐私
     */
    public void privacyConsent() {
        mActivity = (Activity) getPresenterContext();
        if (!AppCookie.getBooleanValue(AppCookie.KEY_AGREE_PRIVACY, false)) {
            if (privacyfirstTipsDialog == null) {
                privacyfirstTipsDialog = new PrivacyFirstTipsDialog.Builder(mActivity, privacyListener).create();
            }
            privacyfirstTipsDialog.show();
        } else {
            permissionProcess();
        }
    }

    /*********
     *
     * 获取im的配置
     *
     */
    public void getImConfig() {
        getData(0, AppConfig.CONFIG_URL, ImConfigBean.class, false);
    }

    /**
     * 定位权限处理
     */
    @SuppressLint("CheckResult")
    public void permissionProcess() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission((Activity) getPresenterContext()).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    interval();
                } else {
                    new AlertDialog.Builder(mActivity).setTitle("需要定位权限")
                            .setMessage("位置权限已关闭，开启以便滴房车正常使用")
                            .setNegativeButton("取消", (dialogInterface, i) -> {
                                mActivity.finish();
                                dialogInterface.dismiss();
                            })
                            .setPositiveButton("设置", (dialogInterface, i) -> {
                                Intent in = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                        .setData(Uri.fromParts("package", getPresenterContext().getPackageName(), null));
                                mActivity.startActivityForResult(in, CODE_REQUEST_POISITION);
                                dialogInterface.dismiss();
                            }).setCancelable(false).show();
                }
            });
        } else {
            interval();
        }
    }

    /**
     * 计时器
     */
    private void interval() {
        mDisposable = Flowable.interval(1, TimeUnit.SECONDS)
                .doOnNext(aLong -> {
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    try {
                        String token = Cookie.getStringValue(null, SPConstance.USER_JSON_TOKEN, "");
                        String tokenTime = Cookie.getStringValue(null, SPConstance.USER_JSON_TOKE_TIME, "");
                        if (!TextUtils.isEmpty(token)) {
                            OkGoUtil.setToken(token, tokenTime);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    go();
                });

    }

    private void go() {
        if (AppCookie.getBooleanValue("first_open", true)) {
            AppCookie.save("first_open", false);
            mActivity.startActivity(GuideActivity.getIntent(mActivity));
        } else {
            mActivity.startActivity(MainActivity.getIntent(mActivity));
        }
        mActivity.finish();
    }

    @Override
    public void detachView() {
        super.detachView();
        stopCarousel();
    }

    /**
     * 停止计时
     */
    public void stopCarousel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    private PrivacyFirstTipsDialog.PrivacyListener privacyListener = new PrivacyFirstTipsDialog.PrivacyListener() {
        @Override
        public void agree() {
            AppCookie.save(AppCookie.KEY_AGREE_PRIVACY, true);
            permissionProcess();
        }

        @Override
        public void disAgree() {
            if (privacySecondTipsDialog == null) {
                privacySecondTipsDialog = new PrivacySecondTipsDialog.Builder(mActivity, privacyListener1).create();
            }
            privacySecondTipsDialog.show();
        }
    };

    private PrivacySecondTipsDialog.PrivacyListener privacyListener1 = new PrivacySecondTipsDialog.PrivacyListener() {
        @Override
        public void disAgree() {
            if (privacyThirdTipsDialog == null) {
                privacyThirdTipsDialog = new PrivacyThirdTipsDialog.Builder(mActivity, privacyListener2).create();
            }
            privacyThirdTipsDialog.show();
        }

        @Override
        public void watchAgreement() {
            privacyfirstTipsDialog.show();
        }
    };

    private PrivacyThirdTipsDialog.PrivacyListener privacyListener2 = new PrivacyThirdTipsDialog.PrivacyListener() {
        @Override
        public void watchAgreement() {
            privacyfirstTipsDialog.show();
        }

        @Override
        public void exit() {
            mActivity.finish();
        }
    };
}
