package com.yyrh.core.impl.floatball;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.text.TextUtils;

import com.yyrh.core.entity.SdkBackLoginInfo;
import com.yyrh.core.impl.floatball.FloatCenterService.FloatCenterServiceBinder;
import com.yyrh.utils.YYLog;

/**
 * @author #Suyghur.
 * Created on 2021/10/21
 */
public class FloatCenterServiceManager {

    private volatile static FloatCenterServiceManager INSTANCE = null;

    private FloatCenterService service = null;
    private Activity activity = null;
    private Intent intent = null;
    private boolean isBindService = false;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            service = ((FloatCenterServiceBinder) iBinder).getService();
            service.initService(activity);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

    public void init(Activity activity) {
        this.activity = activity;
        if (service == null) {
            intent = new Intent(activity.getApplicationContext(), FloatCenterService.class);
            activity.getApplicationContext().startService(intent);
            activity.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
            isBindService = true;
        }
    }

    public void attach() {
        if (service == null) {
            YYLog.e("浮标服务未初始化或发生异常");
            return;
        }
        if (!TextUtils.isEmpty(SdkBackLoginInfo.getInstance().userId)) {
            service.attach();
        } else {
            detach();
        }
    }

    public void detach() {
        if (service == null) {
            return;
        }
        service.detach();
    }

    public void release() {
        if (service == null) {
            return;
        }
        service.release();
        if (isBindService) {
            activity.getApplicationContext().unbindService(serviceConnection);
            activity.getApplicationContext().stopService(intent);
        }
        intent = null;
        activity = null;
        serviceConnection = null;
    }

}
