package com.cooleshow.student.ui.live.floatPop;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.List;

import androidx.annotation.Nullable;
import cn.rongcloud.rtc.api.stream.RCRTCVideoView;

/**
 * Author by pq, Date on 2022/5/13.
 */
public class FloatingWindowService extends Service implements FloatWindowHelper.OnEventListener {
    public static final String CLASS_PATH = "com.cooleshow.student.ui.live.floatPop.FloatingWindowService";
    private FloatWindowHelper mHelper;
    private boolean isShowing = false;
    private MyBinder mBinder;

    @Override
    public void onCreate() {
        super.onCreate();
        mHelper = new FloatWindowHelper(this, this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (mBinder == null) {
            mBinder = new MyBinder();
        }
        boolean isPc = intent.getBooleanExtra("isPc", true);
        if (mHelper != null && !isShowing) {
            mHelper.setLiveFromPc(isPc);
            mHelper.showFloatingWindowView(this);
            isShowing = true;
        }
        return mBinder;
    }

    @Override
    public void onDestroy() {
        // 移除浮动框
        if (mHelper != null) {
            mHelper.dismiss();
        }
        if (mBinder != null) {
            if (mBinder.eventListener != null) {
                mBinder.eventListener.onServiceDestroy();
            }
        }
        super.onDestroy();
        Log.i("pq", "FloatingWindowService onDestroy");
    }

    @Override
    public void onClose() {
        if (mBinder != null && mBinder.eventListener != null) {
            mBinder.eventListener.onUnbindService();
        }
    }

    public class MyBinder extends Binder {
        private OnEventListener eventListener;

        public FloatingWindowService getService() {
            return FloatingWindowService.this;
        }

        public void addVideoView(List<RCRTCVideoView> videoViews) {
            if (mHelper != null) {
                mHelper.addVideoView(videoViews);
            }
        }

        public void setOnEventListener(OnEventListener eventListener) {
            this.eventListener = eventListener;
        }
    }

    public interface OnEventListener {
        void onServiceDestroy();

        void onUnbindService();
    }
}
