package com.hh.arome.utils;

import static android.content.Context.BIND_AUTO_CREATE;

import static com.hh.lib_base.Constants.LogcatValue.LINE;
import static com.hh.lib_base.Constants.LogcatValue.LOG_NODE_AIDL;
import static com.hh.lib_base.Constants.LogcatValue.LOG_NODE_DEVICE;
import static com.hh.lib_base.Constants.LogcatValue.NET_LOGCAT;
import static com.hh.lib_base.Constants.LogcatValue.NODE;
import static com.hh.lib_base.Constants.LogcatValue.WARP;
import static com.hh.lib_base.Constants.SERVER_ACTION.CLOSE_APP;
import static com.hh.lib_base.Constants.SERVER_ACTION.REBOOT;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.hh.arome.BuildConfig;
import com.hh.arome.MyApp;
import com.hh.arome.services.keeplive.MyJobService;
import com.hh.hhomc.AppMessageBean;
import com.hh.hhomc.IAidlCallBack;
import com.hh.hhomc.IAidlInterface;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.LogType;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.log.bean.LogcatAddRequestBean;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_base.utils.device.DeviceUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * @author xwh
 * time 2024/8/21
 * Description: $
 **/
public class AIDLUtils {

    private volatile static AIDLUtils aidlUtils;
    private volatile AIDLCallBack callBack;
    private String aidlSender = "HHArome";    // aidl消息发送者，标识收到的消息来自哪个app

    public static AIDLUtils getInstance() {
        if (aidlUtils == null) {
            synchronized (AIDLUtils.class) {
                if (aidlUtils == null) {
                    aidlUtils = new AIDLUtils();
                }
            }
        }
        return aidlUtils;
    }

    public void bindService(Context context) {

        AppLogUtils.e("bindService");
        Intent intent = new Intent();
        // 对应服务端AndroidManifest.xml配置service action:name
        String ACTION = "com.hh.hhomc.services.AidlService";
        intent.setAction(ACTION);
        // 对应服务端AndroidManifest.xml package,可能会是测试包，注意打印对应服务端app包名，不然会连不上
        intent.setPackage(BuildConfig.AIDL_SERVER_APP_PACKAGE_NAME);
        context.bindService(intent, serviceConnection, BIND_AUTO_CREATE);

    }

    IAidlInterface iAidlInterface;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            AppLogUtils.e("onServiceConnected");
            iAidlInterface = IAidlInterface.Stub.asInterface(iBinder);
            AppLogUtils.e("onServiceConnected--iAidlInterface--" + iAidlInterface);
            try {
                iAidlInterface.asBinder().linkToDeath(mDeathRecipient, 0);
                iAidlInterface.registerCallBack(iAidlCallBack);


                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "AIDL---消息通道成功---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("sn = ").append(DeviceUtils.getDeviceSN()).append(WARP)
                        .append("arome包名 = ").append(DeviceUtils.getAppPackageName(BaseApplication.getContext())).append(WARP)
                        .append("arome版本号 = ").append(DeviceUtils.getAppVersionName(BaseApplication.getContext()));

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );
                UploadLogUtils.sendLogs(logNode,LOG_NODE_AIDL,logLine,logContentSb.toString());



                // 发送消息
//                sendAppInfoMessage();

                // 发送消息
//                if (iAidlInterface != null) {
//                    AppMessageBean sendBean = new AppMessageBean();
//                    sendBean.setBusinessAppPackageName(DeviceUtils.getAppPackageName(mActivity));
//                    sendBean.setBusinessAppVersionName(DeviceUtils.getAppVersionName(mActivity));
//                    iAidlInterface.setAppMessageBean(sendBean);
//                    AppLogUtils.e("发送消息");
//                }


            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        //当承载IBinder的进程消失时接收回调的接口
        @Override
        public void binderDied() {
            if (null == iAidlInterface) {
                return;
            }
            iAidlInterface.asBinder().unlinkToDeath(mDeathRecipient, 0);
            iAidlInterface = null;
            //断线重来逻辑
        }
    };
    private IAidlCallBack iAidlCallBack = new IAidlCallBack.Stub() {
        @Override
        public void onMessageSuccess(AppMessageBean appMessageBean) throws RemoteException {
            AppLogUtils.e("IAidlCallBack---getAppMessageBean" + appMessageBean.toString());
            // TODO 这里就是接收到hhomc发送的消息，开始处理对应业务逻辑
            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
            if (appMessageBean != null) {
                AppLogUtils.e("接收消息 = " + appMessageBean.toString());
                String op = appMessageBean.getOp();

                if (CLOSE_APP.equals(op)) {
                    AppLogUtils.e("接收消息CLOSE_APP");

                    String businessAppPackageName = appMessageBean.getBusinessAppPackageName();
                    AppLogUtils.e("接收消息CLOSE_APP---businessAppPackageName = " + businessAppPackageName);

                    // 日志开始----------------begin
                    // 日志行数——对应web端"日志标签"
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    // 日志节点
                    String logNode = "AIDL---接收消息---";
                    // 日志内容
                    StringBuilder logContentSb = new StringBuilder();
                    logContentSb.append(logNode).append(WARP)
                            .append("sn = ").append(DeviceUtils.getDeviceSN()).append(WARP)
                            .append("arome包名 = ").append(DeviceUtils.getAppPackageName(BaseApplication.getContext())).append(WARP)
                            .append("arome版本号 = ").append(DeviceUtils.getAppVersionName(BaseApplication.getContext())).append(WARP)
                            .append("appMessageBean = ").append(appMessageBean.toString());
                    ;

                    // 开始保存本地日志
                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                            .append(LINE)
                            .append(logLine).append(WARP)
                            .append(NODE)
                            .append(logContentSb)
                            .toString()
                    );

                    UploadLogUtils.sendLogs(logNode,LOG_NODE_AIDL,logLine,logContentSb.toString());


                    if (StringUtils.isNull(businessAppPackageName)) {
                        return;
                    } else if (businessAppPackageName.equals(DeviceUtils.getAppPackageName(BaseApplication.getContext()))) {
                        AppLogUtils.e("包名一致，开始关闭App");
                        if (callBack != null) {
                            MyJobService.Companion.stopJob(MyApp.getContext());
                            callBack.closeApp();
                        }
                    }

                } else if (REBOOT.equals(op)) {
                    if (callBack != null) {
                        callBack.reboot();
                    }

                }
            }
        }


//        @Override
//        public void setAppMessageBean(AppMessageBean appMessageBean) throws RemoteException {
//            AppLogUtils.e("IAidlCallBack---setAppMessageBean");
//            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
//            if (getBean != null) {
//                AppLogUtils.e("接受消息");
//                String businessAppPackageName = getBean.getBusinessAppPackageName();
//                String businessAppVersionName = getBean.getBusinessAppVersionName();
//                String op = getBean.getOp();
//
//                AppLogUtils.e("接受消息----businessAppPackageName  " + businessAppPackageName);
//                AppLogUtils.e("接受消息----businessAppVersionName  " + businessAppVersionName);
//                AppLogUtils.e("接受消息----op  " + op);
//
//                closeApp();
//
//            }
//        }
//
//        @Override
//        public AppMessageBean getAppMessageBean() throws RemoteException {
//            AppLogUtils.e("IAidlCallBack---getAppMessageBean");
//            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
//            if (getBean != null) {
//                AppLogUtils.e("接受消息");
//                String businessAppPackageName = getBean.getBusinessAppPackageName();
//                String businessAppVersionName = getBean.getBusinessAppVersionName();
//
//                AppLogUtils.e("接受消息----businessAppPackageName  " + businessAppPackageName);
//                AppLogUtils.e("接受消息----businessAppVersionName  " + businessAppVersionName);
//            }
//
//
//            return getBean;
//        }

    };


    private void sendAppInfoMessage() {
        // 发送消息
        if (iAidlInterface != null) {
            try {


                String appPackageName = DeviceUtils.getAppPackageName(BaseApplication.getContext());
                String appVersionName = DeviceUtils.getAppVersionName(BaseApplication.getContext());

                AppLogUtils.e("appPackageName--" + appPackageName);
                AppLogUtils.e("appVersionName--" + appVersionName);

                AppMessageBean sendBean = new AppMessageBean();
                sendBean.setBusinessAppPackageName(appPackageName + "");
                sendBean.setBusinessAppVersionName(appVersionName + "");
                sendBean.setSender(aidlSender);
                sendBean.setSender(DeviceUtils.getDeviceSN());

                iAidlInterface.setAppMessageBean(sendBean);
            } catch (RemoteException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                AppLogUtils.e("发送消息--NullPointerException");
                e.printStackTrace();
            }
            AppLogUtils.e("发送消息");
        } else {
            AppLogUtils.e("发送消息---iAidlInterface");
        }
    }

    public void setAIDLCallBack(AIDLCallBack callBack) {
        this.callBack = callBack;
    }

    public void unbindService(Context context) {
        //解除注册
        if (null != iAidlInterface && iAidlInterface.asBinder().isBinderAlive()) {
            try {
                iAidlInterface.unregisterCallBack(iAidlCallBack);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //解除绑定服务
        if (null != serviceConnection) {
            context.unbindService(serviceConnection);
        }


    }

    public interface AIDLCallBack {
        void reboot();

        void closeApp();
    }

    public void onRelease(){
        aidlUtils=null;
    }

}
