package com.aros.apron.tools;


import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

import com.aros.apron.app.ApronApp;
import com.aros.apron.callback.MqttActionCallBack;
import com.aros.apron.callback.MqttCallBack;
import com.aros.apron.constant.AMSConfig;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.util.Random;

public class MqttManager {

    public MqttAndroidClient mqttAndroidClient; //ltz change
    public MqttConnectOptions mMqttConnectOptions;
    String TAG = getClass().getSimpleName();

    private MqttManager() {
    }

    private static class MqttHolder {
        private static final MqttManager INSTANCE = new MqttManager();
    }

    public static MqttManager getInstance() {
        return MqttHolder.INSTANCE;
    }

    public void needConnect() {
        initMqttClientParams();
    }

    private void initMqttClientParams() {
        mqttAndroidClient = new MqttAndroidClient(ApronApp.Companion.getApplication(), AMSConfig.getInstance().getMqttServerUri(), generateRandomString(10));
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setAutomaticReconnect(true); //ltz add
        mMqttConnectOptions.setMaxInflight(1000);// 增加最大并发未确认消息数量
        mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
        mMqttConnectOptions.setConnectionTimeout(30); //设置超时时间，单位：秒 ltz denote
        mMqttConnectOptions.setKeepAliveInterval(20); //设置心跳包发送间隔，单位：秒 ltz denote
        mMqttConnectOptions.setUserName(AMSConfig.getInstance().getUserName()); //设置用户名
        mMqttConnectOptions.setPassword(AMSConfig.getInstance().getPassword().toCharArray()); //设置密码
        mqttAndroidClient.setCallback(new MqttCallBack()); //设置监听订阅消息的回调
        doClientConnection();
    }



    /**
     * 连接MQTT服务器
     */
    private void doClientConnection() {
        if (!mqttAndroidClient.isConnected() && isConnectIsNomarl()) {
            try {
                mqttAndroidClient.connect(mMqttConnectOptions, null, new MqttActionCallBack(mqttAndroidClient,mMqttConnectOptions));
            } catch (MqttException e) {
                LogUtil.log(TAG,"mqtt连接异常:"+e.toString());
                e.printStackTrace();
            }
        }

    }

    /**
     * 判断网络是否连接
     */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) ApronApp.Companion.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            LogUtil.log(TAG, "当前网络名称：" + name);
            return true;
        } else {
            LogUtil.log(TAG, "没有可用Mqtt网络,延迟三秒后重连");
            /*没有可用网络的时候，延迟3秒再尝试重连*/
            doConnectionDelay();
            return false;
        }
    }


    /**
     * 没有可用网络的时候，延迟5秒再尝试重连
     */
    private void doConnectionDelay() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doClientConnection();
            }
        }, 3000);
    }

    private String generateRandomString(int length) {
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            builder.append(characters.charAt(index));
        }
        return builder.toString();
    }
}
