package com.hh.hhomc.services;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;

import androidx.annotation.Nullable;

import com.common.lib_base.utils.log.AppLogUtils;
import com.hh.hhomc.IAidlInterface;
import com.hh.hhomc.AppMessageBean;
import com.hh.hhomc.IAidlCallBack;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AidlService extends Service {
    private RemoteCallbackList<IAidlCallBack> callbackList = new RemoteCallbackList<>();

    AppMessageBean bean = new AppMessageBean();

    private Lock mLock = new ReentrantLock();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private final IAidlInterface.Stub binder = new IAidlInterface.Stub() {
        @Override
        public void registerCallBack(IAidlCallBack iAidlCallBack) throws RemoteException {
            callbackList.register(iAidlCallBack);
        }

        @Override
        public void unregisterCallBack(IAidlCallBack iAidlCallBack) throws RemoteException {
            callbackList.unregister(iAidlCallBack);
        }

        @Override
        public void setAppMessageBean(AppMessageBean appMessageBean) throws RemoteException {

//            bean = appMessageBean;

//            mLock.lock();
//            try {
            bean = appMessageBean;
            try {
                final int num = callbackList.beginBroadcast();
                AppLogUtils.e("num--" + num);
                for (int i = 0; i < num; i++) {
                    IAidlCallBack iAidlCallBack = callbackList.getBroadcastItem(i);

                    AppLogUtils.e("iAidlCallBack--" + iAidlCallBack);

                    iAidlCallBack.onMessageSuccess(appMessageBean);
                }

            } catch (RemoteException e) {
                // 当通知业务app关闭时，出现android.os.DeadObjectException
                AppLogUtils.e("RemoteException--e---" + e.toString());
                e.printStackTrace();
            } finally {
                // 上面的异常导致aild beginBroadcast() called while already in a broadcast，故finally中来finishBroadcast
                callbackList.finishBroadcast();
            }
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                mLock.unlock();
//            }


        }

        @Override
        public AppMessageBean getAppMessageBean() throws RemoteException {
            return bean;
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();
    }
}