import Codes from "./enum/Codes.js"
import {eventsManager} from "./EventsManager.js"
import ECurrentShaderMode from "./enum/ECurrentShaderMode.js"
import Actions from "./enum/Actions.js"
import PointType from "./enum/PointType.js"
import Logger from "./Logger.js"
import util from "./util.js"

const logger = new Logger('xverse-signal')
export default class Signal {
    constructor(e) {
        this.signalHandleActived = !0
        this.isUpdatedYUV = !0
        this._room = e
    }
    handleSignal(e) {
        var a, s, newUserStates;
        if (!this.signalHandleActived)
        {
            return;
        }
        console.log('执行handleSignal：'+JSON.stringify(e.signal))
        const {signal: signal, alreadyUpdateYUV: alreadyUpdateYUV} = e;
        this.handleActionResponses(signal);
        //this._room.handleSignalHook(signal);
        //视频流没有传送就不能执行
        if (!alreadyUpdateYUV) {
            const u = (a = signal.newUserStates) == null ? void 0 : a.find(c=>c.userId === this._room.userId);
            if ((u == null ? void 0 : u.renderInfo) && ((s = this._room._userAvatar) == null ? void 0 : s.isMoving)) {
                logger.debug("stream stoped, make avatar to stop");
                const {isMoving: c, isRotating: h} = u.renderInfo;
                this._room.avatarManager._updateAvatarMovingStatus({
                    id: u.userId,
                    isMoving: !!c,
                    isRotating: !!h
                })
            }
            return
        }


        this.isUpdatedYUV = alreadyUpdateYUV;
        const receiveSignal = signal;
        if (!signal) {
            logger.warn("metadata signal is empty");
            return
        }
        if (receiveSignal.code === Codes.RepeatLogin) {
            this._room.handleRepetLogin();
            return
        }
        if(receiveSignal.code !== void 0 && receiveSignal.code !== Codes.Success && receiveSignal.code !== Codes.ActionMaybeDelay && receiveSignal.code !== Codes.DoActionBlocked && receiveSignal.code !== Codes.GetOnVehicle){
            logger.error("signal errcode: ", receiveSignal)
            this._room.emit("error", receiveSignal)
        }
        if(!window.isUser && receiveSignal.newUserStates){
            receiveSignal.newUserStates[0].userId = nickname
            receiveSignal.newUserStates[0].playerState.nickName = nickname
            window.isUser = true
          }

        newUserStates = receiveSignal.newUserStates
        let currentUserStates = void 0 
        if(newUserStates != null){
            currentUserStates = newUserStates.find(u=>u.userId === this._room.userId);
        }
        
        if (receiveSignal.broadcastAction)
        {
            try {
                const u = JSON.parse(receiveSignal.broadcastAction.data);
                Broadcast.handlers.forEach(c=>c(u))
            } catch (u) {
                logger.error(u)
            }
        }

        receiveSignal.newUserStates && receiveSignal.newUserStates.length > 0 && this._room.avatarManager.handleAvatar(receiveSignal);
        if (currentUserStates != null && currentUserStates.playerState) {
            this._room._currentClickingState = currentUserStates.playerState;
            const {pathName: pathName, attitude: attitude, areaName: areaName, skinId: skinId} = currentUserStates.playerState;

            if(pathName){
                this._room.pathManager.currentPathName = pathName;
                this._room.updateCurrentState({
                    pathName: pathName
                })
            }
            skinId && this.udpateSkinInfo(skinId);
            areaName && this._room.updateCurrentState({
                areaName: areaName
            });

            if (attitude) {
                const d = this._room.skin.routeList.find(g=>g.areaName === this._room.currentState.areaName)
                const speed = ((d == null ? void 0 : d.step) || 7.5) * 30;
                this._room.updateCurrentState({
                    speed: speed,
                    attitude: attitude
                }),
                this._room.pathManager.currentAttitude = attitude,
                this._room._userAvatar && (this._room._userAvatar.motionType = attitude)
            }
            if(this._room.sceneManager.getCurrentShaderMode() !== ECurrentShaderMode.pano && !this._room.isPano && currentUserStates.playerState.camera){
                // console.error(currentUserStates.playerState)
                this._room.camera.setCameraPose(currentUserStates.playerState.camera)

                //console.log('接收数据setCameraPose：'+JSON.stringify(currentUserStates.playerState.camera.angle))
                //console.log('我们计算：'+ util.ue4Rotation2Xverse(currentUserStates.playerState.camera.angle).y/Math.PI*180)
            }
        }
        currentUserStates != null && currentUserStates.renderInfo && this._room.camera.handleRenderInfo(currentUserStates)
        if (receiveSignal.actionType !== void 0) {
            const {actionType: actionType, code: code, echoMsg: echoMsg, traceId: traceId} = receiveSignal;
            if(actionType === Actions.Echo && code === Codes.Success){
                this._room.networkController.rtcp.heartbeat.pong(echoMsg, traceId)
            }

            if(code !== Codes.Success){
                eventsManager.remove(traceId, code)
            }
            else if([Actions.GetReserveStatus, Actions.Broadcast, Actions.ChangeNickname, Actions.ConfirmEvent, Actions.ReserveSeat, Actions.Rotation, Actions.TurnTo, Actions.RotateTo, Actions.SetPlayerState, Actions.GetNeighborPoints, Actions.TurnToFace, Actions.AudienceChangeToVisitor, Actions.RemoveVisitor, Actions.GetUserWithAvatar].includes(actionType)){
                eventsManager.remove(traceId, code, receiveSignal)
            }
        }
    }
    handleActionResponses(responseData) {

        if(responseData != null && responseData.actionResponses&&responseData.actionResponses.length != 0){
            responseData.actionResponses.forEach(actionResponse=>{
                if (actionResponse.actionType == null)
                {
                    return;
                }
                const {pointType: pointType, extra: extra, actionType: actionType, traceId: traceId, code: code, msg: msg} = actionResponse;
                if(actionType === Actions.GetNeighborPoints){
                    eventsManager.remove(traceId, code, actionResponse.nps)
                }
                else if(actionType === Actions.GetUserWithAvatar){
                    eventsManager.remove(traceId, code, actionResponse.userWithAvatarList)
                }
                else{
                    eventsManager.remove(traceId, code, msg)
                }

                if(pointType === PointType.Path && actionType === Actions.Clicking){
                    this._room.moveToExtra = decodeURIComponent(extra)
                }
            })
        }
    }
    async udpateSkinInfo(e) {
        this._room.updateCurrentState({
            skinId: e
        });
        const t = await this._room.skinList.find(r=>r.id === e);
        t && this._room.updateCurrentState({
            skin: t
        })
    }
}