package com.mints.goodmoney.manager;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonObject;
import com.mints.goodmoney.MintsApplication;
import com.mints.goodmoney.common.DeviceInfo;
import com.mints.goodmoney.mvp.model.BaseResponse;
import com.mints.goodmoney.mvp.model.Device;
import com.mints.goodmoney.net.LoanService;
import com.mints.library.net.NetCommon;
import com.mints.library.net.netstatus.NetUtils;
import com.mints.library.utils.TLog;
import com.mints.library.utils.json.JsonUtil;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 描述：极光推送管理器
 * 作者：孟崔广
 * 时间：2019/10/5 13:54
 * 邮箱：mengcga@163.com
 */
public class JpushManager {

    private static final String TAG_LOG = "JpushManager";

    private static JpushManager _inst;
    private Context c;

    private static final int MSG_SET_SERVICE = 1002;
    private static final int MSG_SET_ALIAS = 1001;

    public static JpushManager getInstance() {
        if (_inst != null) {
            return _inst;
        } else {
            _inst = new JpushManager();
            return _inst;
        }
    }

    private JpushManager() {
        init();
        return;
    }

    private void init() {
        c = MintsApplication.getContext();
    }

    /**
     * 绑定极光和自己的服务器
     *
     * @param uid 用户信息
     */
    public void setJpushService(String uid) {

        if (c == null || TextUtils.isEmpty(uid))
            return;

        Device device = new Device();
        device.setDevicetype(1);
        device.setUid(uid);
        device.setJgid(JPushInterface.getRegistrationID(c));
        device.setDeviceinfo(DeviceInfo.Companion.getInstance().getMobileModel());

        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_SERVICE, JsonUtil.toJson(device)));
    }


    /**
     * 绑定极光通讯（别名）
     */
    public void setJpushAlias() {

        if (c == null)
            return;

        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, "android"));

    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_SERVICE:
                    TLog.d(TAG_LOG, "Set service in handler.");
                    userBindingJpush((String) msg.obj);
                    break;
                case MSG_SET_ALIAS:
                    TLog.d(TAG_LOG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(c, (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    TLog.d(TAG_LOG, "Unhandled msg - " + msg.what);
                    break;
            }
        }
    };

    /**
     * 绑定用户
     *
     * @param jsondata
     */
    public void userBindingJpush(String jsondata) {
        MintsApplication loanApplication = (MintsApplication) this.c;
        LoanService loanService = loanApplication.getLoanService();

        HashMap<String, Object> vo = new HashMap<>();
        vo.put("uploadData", jsondata);

        loanService.registerDevice(vo)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(loanApplication.defaultSubscribeScheduler())
                .subscribe(new Subscriber<BaseResponse<JsonObject>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (NetUtils.isNetworkConnected(c) && NetCommon.httpErrorCode(e) != 500) {
                            mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_SERVICE, jsondata), 1000 * 60);
                        } else {
                            TLog.d(TAG_LOG, "No network");
                        }
                    }

                    @Override
                    public void onNext(BaseResponse<JsonObject> baseResponse) {
                        int code = baseResponse.getStatus();
                        switch (code) {
                            case 200:
                            case 401:
                            case 404:
                                break;

                            default:
                                if (NetUtils.isNetworkConnected(c)) {
                                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_SERVICE, jsondata), 1000 * 60);
                                } else {
                                    TLog.d(TAG_LOG, "No network");
                                }
                                break;
                        }

                    }
                });
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    TLog.i(TAG_LOG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    TLog.i(TAG_LOG, logs);
                    if (NetUtils.isNetworkConnected(c)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 2000 * 60);
                    } else {
                        Log.i(TAG_LOG, "No network");
                    }
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    TLog.e(TAG_LOG, logs);
            }
        }
    };


}
