package com.daya.live_teaching.repository;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.data.net.RetrofitFactory;
import com.cooleshow.base.utils.SystemUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.api.LiveTeachingApi;
import com.daya.live_teaching.api.WhiteBoardApi;
import com.daya.live_teaching.api.retrofit.CallBackWrapper;
import com.daya.live_teaching.api.retrofit.RetrofitClient;
import com.daya.live_teaching.api.retrofit.RetrofitUtil;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.LoginResult;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.rtc.RtcManager;

import java.util.HashMap;
import java.util.List;


/**
 * 用户数据仓库
 */
public class UserRepository extends BaseRepository {
    private LiveTeachingApi sealClassService;
    private WhiteBoardApi whiteBoardService;
    public static String imToken;

    public UserRepository(Context context) {
        super(context);
        sealClassService = getService(LiveTeachingApi.class);
        whiteBoardService = RetrofitFactory.Companion.getInstance().create(WhiteBoardApi.class);
    }

    public static String authorization;

    public void login(String roomId, boolean isListener, String userName, String imToken, final ResultCallback<LoginResult> callBack) {
        this.imToken = imToken;
        login(roomId, isListener, userName, callBack);
    }

    //加入房间
    public void login(String roomId, boolean isListener, String userName, final ResultCallback<LoginResult> callBack) {
        HashMap<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("roomId", roomId);
        bodyMap.put("audience", String.valueOf(isListener));
        bodyMap.put("userName", userName);
        authorization = UserHelper.getUserToken();
        getHttpManager().setAuthHeader(authorization);
        sealClassService.login(RetrofitUtil.createJsonRequest(bodyMap)).enqueue(new CallBackWrapper<>(new ResultCallback<LoginResult>() {
            @Override
            public void onSuccess(final LoginResult result) {
                if (result == null) {
                    joinRoomStatusNotify(roomId, UserHelper.getUserId(), true);
                    callBack.onFail(-1, "加入房间失败");
                    return;
                }
                // 进入音视频房间
                RtcManager.getInstance().joinRtcRoom(result.roomId, new ResultCallback<String>() {
                    @Override
                    public void onSuccess(String rtcRoomId) {
                        UserInfo roomMember = result.roomMember;
                        if (roomMember != null) {
                            if (roomMember.getRole() == Role.LECTURER) {
                                List<ClassMember.ScheduleStudentMusicScoresBean> userMusicScoresBeans = roomMember.getScheduleStudentMusicScores();
                                List<ClassMember> members = result.roomMemberList;
                                if (userMusicScoresBeans != null && userMusicScoresBeans.size() > 0 && members != null && members.size() > 0) {
                                    for (ClassMember.ScheduleStudentMusicScoresBean scoresBean : userMusicScoresBeans) {
                                        int downStatus = 1;
                                        if (scoresBean != null) {
                                            for (ClassMember member : members) {
                                                if (member.getRole() != Role.LECTURER) {
                                                    member.setPlayMidiJson(result.midiJson);
                                                    List<ClassMember.ScheduleStudentMusicScoresBean> memberMusicScoresBeans = member.getScheduleStudentMusicScores();
                                                    for (ClassMember.ScheduleStudentMusicScoresBean memberScoresBean : memberMusicScoresBeans) {
                                                        if (memberScoresBean != null &&
                                                                scoresBean.getMusicScoreAccompanimentId().equals(memberScoresBean.getMusicScoreAccompanimentId()) && memberScoresBean.getDownStatus() != 1) {
                                                            downStatus = scoresBean.getDownStatus();
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            scoresBean.setDownStatus(downStatus);
                                            scoresBean.setIsAccompaniment(TextUtils.isEmpty(scoresBean.getUrl()) ? 1 : 0);
                                        }
                                    }
                                }
                                roomMember.setScheduleStudentMusicScores(userMusicScoresBeans);
                            }

                            callBack.onSuccess(result);
                        } else {
                            callBack.onFail(-1, "加入房间错误，请重试");
                        }

                    }

                    @Override
                    public void onFail(int errorCode, String errMsg) {
                        callBack.onFail(errorCode, errMsg);
                        joinRoomStatusNotify(result.getRoomId(), UserHelper.getUserId(), false);
                    }
                });


            }

            @Override
            public void onFail(int errorCode, String errMsg) {
                callBack.onFail(errorCode, errMsg);
            }
        }));

    }

    /**
     * 同步房间状态
     */
    public void joinRoomStatusNotify(String roomId, String userId, boolean requestStatus) {
        HashMap<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("roomId", roomId);
        bodyMap.put("userId", userId);
        bodyMap.put("requestStatus", requestStatus);
        bodyMap.put("deviceNum", (TextUtils.isEmpty(BaseApplication.Companion.getRegistrationId()) ? SystemUtils.getUniqueIdentificationCode(getContext()) : BaseApplication.Companion.getRegistrationId()));
        sealClassService.joinRoomStatusNotify(RetrofitUtil.createJsonRequest(bodyMap)).enqueue(new CallBackWrapper<>(new ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onFail(int errorCode, String errorStr) {

            }
        }));
    }
}
