package com.sheep.gamegroup.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.SdkLoginUser;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

/**
 * 游戏认证
 * Created by ljy on 2018/9/12.
 */

public class CertificationUtil {

    private static CertificationUtil certificationUtil;

    public static CertificationUtil newInstance(){
        if(certificationUtil == null)
            certificationUtil = new CertificationUtil();
        return certificationUtil;
    }


    /**
     * 退出app
     * @param errorMsg
     */
    public void showCertificationErrorAndExitApp(final String errorMsg, long skip_time) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                SheepApp.getInstance().setGamePackgeName("");
                SheepApp.getInstance().setGameCode("");
                SheepApp.getInstance().setGameFlag(false);
                ActivityManager.getInstance().finishAllActivity();
            }
        }, skip_time);
    }
    /**
     * 跳转回，游戏
     */
    public void doCertification(final Context context, String token, String packageName, String ext){
        try {
            Log.e("game_-packgename---"+packageName,"");
            Intent intent = new Intent();
            intent.setClassName(packageName, "com.kfzs.duanduan.data.observer.helper.WhistleActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_key), SheepApp.getInstance().getGameCode());

            if (TextUtils.isEmpty(ext)) {
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_package_extras), "");
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_token), token);
            } else if("delete".equals(ext)){
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_cancel), "delete");
            }else  {
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_package_extras), ext);
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_token), token);
            }
            context.startActivity(intent);
            showCertificationErrorAndExitApp("", 100);
        } catch (Exception e) {
            e.printStackTrace();
            showCertificationErrorAndExitApp("认证失败", 100);
        }
    }
    /**
     * 验证获取数据
     */
    public void authCertificationCode(final Context context, final String token){
        ViewUtil.newInstance().showProgress((Activity) context);
        SheepApp.getInstance().getNetComponent().getApiService().verificationAuth(token, SheepApp.getInstance().getGameCode())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        if(baseMessage != null && baseMessage.getData() != null){
                            Log.e("data-------","");
                            doCertification(context, token,  SheepApp.getInstance().getGamePackgeName(), baseMessage.getData()+"");
                        }else {
                            CertificationUtil.newInstance().showCertificationErrorAndExitApp("请求授权错误 " + (baseMessage == null ? "无数据" : baseMessage.getMsg()),1000);
                        }

                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        CertificationUtil.newInstance().showCertificationErrorAndExitApp("请求授权错误 " + baseMessage.getMsg(),1000);
                    }
                });
    }

    //保存当前登录用户信息到游戏sdk用户登录列表所有数据库中
    public void addCurUserToSdkLoginUser() {
        CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
            @Override
            public void call(UserEntity userEntity) {
                if(userEntity != null){
                    SdkLoginUser newSdkLoginUser = new SdkLoginUser();
                    newSdkLoginUser.setAvatar(userEntity.getAvatar());
                    newSdkLoginUser.setToken(SpUtils.getToken(SheepApp.getInstance()));
                    newSdkLoginUser.setInvitation_code(userEntity.getInvitation_code());
                    newSdkLoginUser.setNickname(userEntity.getNickname());
                    newSdkLoginUser.setServiceName(SheepApp.getInstance().getConnectAddress().name());
                    DDProviderHelper.getInstance().addOrUpdateSdkLoginUser(newSdkLoginUser, null);
                }
            }
        });
    }
}
