package com.bokecc.livemodule.live.multirtc;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.utils.DensityUtil;
import com.bokecc.livemodule.view.BaseRelativeLayout;
import com.bokecc.sdk.mobile.live.common.log.ELog;
import com.bokecc.sdk.mobile.live.stream.RemoteStreamInfo;
import com.bokecc.sdk.mobile.live.stream.live.rtc.HDMediaView;

import java.util.ArrayList;
import java.util.List;

/**
 * 多人连麦可滑动视频组件 RelativeLayout+ScrollView+TextureView，横竖屏支持
 * 竖屏状态下，视频宽高比124dp：70dp
 */
public class MultiRTCVideoLayout extends BaseRelativeLayout {

    private static final String TAG = "MultiRTCVideoLayout";

    private List<MultiRTCVideoItemLayout> mVideoLayoutList = new ArrayList<>();
    private View rootView;
    private LinearLayout rtcVideoContainer;
    private HorizontalScrollView hScrollView;
    private ScrollView vScrollView;

    public static final String SELF_VIDEO_TAG = "tag_mine";

    //竖屏
    private boolean isPortrait = true;


    public MultiRTCVideoLayout(Context context) {
        super(context);
        inflateViews();
    }

    public MultiRTCVideoLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflateViews();
    }

    public MultiRTCVideoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflateViews();
    }

    @Override
    public void initViews() {
    }

    private void inflateViews() {
        rootView = LayoutInflater.from(mContext).inflate(R.layout.live_multi_rtc_video_layout,null);
//        rtcVideoContainer = rootView.findViewById(R.id.ll_live_multi_rtc_container);
        rtcVideoContainer = new LinearLayout(mContext);
        hScrollView = rootView.findViewById(R.id.h_scroll_view);
        vScrollView = rootView.findViewById(R.id.v_scroll_view);
        rootView.setBackgroundColor(Color.parseColor("#FFD8D8D8"));
        addView(rootView);
        refreshView();
    }

    private void refreshView(){
        if (isPortrait){
            vScrollView.removeAllViews();
            vScrollView.setVisibility(View.GONE);
            hScrollView.removeAllViews();
            hScrollView.setVisibility(View.VISIBLE);
            hScrollView.addView(rtcVideoContainer);

            LayoutParams layoutParams = (LayoutParams) rootView.getLayoutParams();
            layoutParams.width = LayoutParams.MATCH_PARENT;
            layoutParams.height = LayoutParams.WRAP_CONTENT;
            rootView.setLayoutParams(layoutParams);

            LayoutParams layoutParams1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
            hScrollView.setLayoutParams(layoutParams1);

            LayoutParams params = (LayoutParams) this.getLayoutParams();
            if (params==null){
                params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
            }
            params.width = LayoutParams.MATCH_PARENT;
            params.height = LayoutParams.WRAP_CONTENT;
            rtcVideoContainer.setOrientation(LinearLayout.HORIZONTAL);
            this.setLayoutParams(params);
        }else {
            hScrollView.removeAllViews();
            hScrollView.setVisibility(View.GONE);
            vScrollView.removeAllViews();
            vScrollView.setVisibility(View.VISIBLE);
            vScrollView.addView(rtcVideoContainer);

            LayoutParams layoutParams = (LayoutParams) rootView.getLayoutParams();
            layoutParams.width = LayoutParams.WRAP_CONTENT;
            layoutParams.height = LayoutParams.MATCH_PARENT;
            rootView.setLayoutParams(layoutParams);

            LayoutParams layoutParams1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
            vScrollView.setLayoutParams(layoutParams1);

            LayoutParams params = (LayoutParams) this.getLayoutParams();
            if (params==null){
                params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
            }
            params.width = LayoutParams.WRAP_CONTENT;
            params.height = LayoutParams.MATCH_PARENT;
            rtcVideoContainer.setOrientation(LinearLayout.VERTICAL);
            this.setLayoutParams(params);
        }

    }

    /**
     * 添加video
     * @param view 预览视图
     * @param userId 流id
     * @param info 当前互动者信息（昵称、麦克风状态、摄像头状态）
     */
    public void addVideo(final HDMediaView view, final String userId,final String role, RemoteStreamInfo info){
        //判空
        if (info==null){
            info = new RemoteStreamInfo();
            info.setUserId(userId);
            info.setAllowAudio(true);
            info.setAllowVideo(true);
            info.setUserName("");
        }
        ELog.d(TAG, "[demo_bokecc.MultiRTCVideoLayout.addVideo]  [view, userId, role, info.video="+info.isAllowVideo()+",info.audio="+info.isAllowAudio()+",info.username="+info.getUserName()+"]");
        final RemoteStreamInfo userInfo = info;
        post(new Runnable() {
            @Override
            public void run() {
                String nickName = userInfo.getUserName();
                MultiRTCVideoItemLayout multiRTCVideoItemLayout = new MultiRTCVideoItemLayout(mContext,view,nickName,userInfo.isAllowVideo());
                int sw = mContext.getResources().getDisplayMetrics().widthPixels;
                int width = (int) (sw*0.2);
                int height = width*9/16;
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width,height);
                layoutParams.setMargins(5,5,5,5);
                multiRTCVideoItemLayout.setLayoutParams(layoutParams);
                if (SELF_VIDEO_TAG.equals(userId)){//自己的预览加到view最前面（本地流）
                    rtcVideoContainer.addView(multiRTCVideoItemLayout,0);
                    mVideoLayoutList.add(0,multiRTCVideoItemLayout);
                }else {//其他学生的预览（远端流）
                    rtcVideoContainer.addView(multiRTCVideoItemLayout);
                    mVideoLayoutList.add(multiRTCVideoItemLayout);
                }
                multiRTCVideoItemLayout.setTag(userId);
            }
        });
    }

    /**
     * 更新item摄像头显示状态
     * @param userId 流id
     * @param isVideoOn 摄像头是否开启
     */
    public void updateItemViewState(final String userId, final boolean isVideoOn){
        post(new Runnable() {
            @Override
            public void run() {
                MultiRTCVideoItemLayout layout = rtcVideoContainer.findViewWithTag(userId);
                if (layout!=null){
                    layout.updateState(isVideoOn);
                }
            }
        });

    }

    /**
     * 移除video
     * @param userId 使用tag获取view
     */
    public void removeVideo(final String userId){
        post(new Runnable() {
            @Override
            public void run() {
                ELog.d(TAG, "[demo_bokecc.MultiRTCVideoLayout.removeVideo]  [userId="+userId+"]");
                MultiRTCVideoItemLayout layout = rtcVideoContainer.findViewWithTag(userId);
                if (layout!=null){
                    rtcVideoContainer.removeView(layout);
                    mVideoLayoutList.remove(layout);
                }
            }
        });
    }

    public void removeAllVideo(){
        post(new Runnable() {
            @Override
            public void run() {
                rtcVideoContainer.removeAllViews();
                mVideoLayoutList.clear();
            }
        });

    }


    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ELog.d(TAG, "[demo_bokecc.MultiRTCVideoLayout.onConfigurationChanged]  [newConfig.land="+(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)+"]");
        if (newConfig!=null){
            if (Configuration.ORIENTATION_LANDSCAPE==newConfig.orientation){
                //横屏
                isPortrait = false;
                refreshView();
            }else {
                isPortrait = true;
                refreshView();
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    public void changeOrientation(boolean land) {
        isPortrait = !land;
        refreshView();
    }
}
