package com.mogo.cloud.live.server;

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

import com.mogo.cloud.live.listener.ILiveCurrentRoomStatusListener;
import com.mogo.cloud.live.listener.IYUVDataListener;
import com.mogo.cloud.live.manager.CameraFrameManager;
import com.mogo.cloud.live.manager.MoGoLiveManager;
import com.mogo.cloud.live.utils.ByteUtils;


public class PushService extends Service
        implements IYUVDataListener, ILiveCurrentRoomStatusListener {
    public static final String ACTION_START_RTMP_PUSH = "action_start_rtmp_push";
    public static final String ACTION_STOP_RTMP_PUSH = "action_stop_rtmp_push";
    public static final String ACTION_FORCED_STOP_RTMP_PUSH = "action_forced_stop_rtmp_push";

    private static final String TAG = "PushService";
    // 自研直播SDK
    private MoGoLiveManager mLivePusher;

    /**
     * 启动服务
     *
     * @param context 上下文
     * @param action  动作标志
     */
    public static void startService(Context context, String action) {
        Intent intent = new Intent(context, PushService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "初始化推流服务……");
        if (mLivePusher == null) {
            mLivePusher = MoGoLiveManager.getInstance();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            // 开启直播
            if (ACTION_START_RTMP_PUSH.equals(intent.getAction())) {
                Log.i(TAG, "接收指令开启直播推送");
                try {
                    startPush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 关闭直播，如果还有人观看不关闭
            else if (ACTION_STOP_RTMP_PUSH.equals(intent.getAction())) {
                Log.i(TAG, "接受指令关闭直播推送");
                if (mLivePusher.getLiveStatusModel().getOnlineNumber() <= 1) {
                    stopPush();
                } else {
                    Log.i(TAG, "房间还有 " + mLivePusher.getLiveStatusModel().getOnlineNumber() + " 位观众，不可以关闭直播");
                }
            }
            // 强制关闭直播
            else if (ACTION_FORCED_STOP_RTMP_PUSH.equals(intent.getAction())) {
                Log.i(TAG, "接收指令强制关闭直播推送");
                stopPush();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLivePusher.removeLiveRoomStatusListener(this);
    }

    /**
     * 启动发布直播视频流
     */
    private void startPush() {
        Log.i(TAG, "startPush");
        if (mLivePusher != null
                && mLivePusher.getLiveStatusModel().isPushing()) {
            Log.w(TAG, "已经开启了推流，无需重复开启");
            return;
        }
        if (mLivePusher != null && !mLivePusher.getLiveStatusModel().isLoginCurrentRoom()) {
            // 设置登录房间的回调监听
            mLivePusher.addLiveRoomStatusListener(this);
            // 推流之前必须先登录房间
            //mLivePusher.loginRoom();
        } else {
            realStartPublish();
        }
    }

    private void realStartPublish() {
        Log.i(TAG, "realStartPublish");
        // 开始发布
        mLivePusher.startPublish();
        // 注册视频YUV回调监听
        CameraFrameManager.getInstance().addYuvDataCallback(this);
    }

    /**
     * 结束发布直播视频流
     */
    private void stopPush() {
        try {
            // 移除登录房间回调
            mLivePusher.removeLiveRoomStatusListener(this);
            // 是否处于发布状态
            if (mLivePusher != null && mLivePusher.getLiveStatusModel().isPushing()) {
                // 停止发布
                mLivePusher.stopPublish();
                // 退出房间
                //mLivePusher.logoutCurrentRoom();
            }
            // 移除视频回碉监听
            CameraFrameManager.getInstance().rmYuvDataCallback(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFrame(byte[] data) {
        if (mLivePusher != null
                && mLivePusher.getLiveStatusModel().isCaptureStatus()
                && mLivePusher.getLiveStatusModel().isPushing()
                && data != null) {
            // 将YUV数据发布到即构
            mLivePusher.startPublishingStream(
                    ByteUtils.getBuffer(data, data.length), data.length,
                    SystemClock.elapsedRealtime());
        }
    }

    @Override
    public void onCurrentRoomConnecting() {

    }

    @Override
    public void onCurrentRoomConnected() {
        Log.i(TAG, "登录房间成功开启推流");
        realStartPublish();
    }

    @Override
    public void onCurrentRoomDisconnected() {

    }

}
