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"

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, l;
        if (!this.signalHandleActived)
        {
            return;
        }
        const {signal: t, alreadyUpdateYUV: r} = e;
        this.handleActionResponses(t);
        //this._room.handleSignalHook(t);
        if (!r) {
            const u = (a = t.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
        }

        //if(t.actionType == 1009){
            console.log('执行signal:'+JSON.stringify(t))
        //}

        this.isUpdatedYUV = r;
        const n = t;
        if (!t) {
            logger.warn("metadata signal is empty");
            return
        }
        if (n.code === Codes.RepeatLogin) {
            this._room.handleRepetLogin();
            return
        }
        n.code !== void 0 && n.code !== Codes.Success && n.code !== Codes.ActionMaybeDelay && n.code !== Codes.DoActionBlocked && n.code !== Codes.GetOnVehicle && (logger.error("signal errcode: ", n),
        this._room.emit("error", n));
        const o = (l = n.newUserStates) == null ? void 0 : l.find(u=>u.userId === this._room.userId);
        if (n.broadcastAction)
            try {
                const u = JSON.parse(n.broadcastAction.data);
                Broadcast.handlers.forEach(c=>c(u))
            } catch (u) {
                logger.error(u)
            }
        if (n.newUserStates && n.newUserStates.length > 0 && this._room.avatarManager.handleAvatar(n),
        o != null && o.playerState) {
            this._room._currentClickingState = o.playerState;
            const {pathName: u, attitude: c, areaName: h, skinId: f} = o.playerState;
            if (u && (this._room.pathManager.currentPathName = u,
            this._room.updateCurrentState({
                pathName: u
            })),
            f && this.udpateSkinInfo(f),
            h && this._room.updateCurrentState({
                areaName: h
            }),
            c) {
                const d = this._room.skin.routeList.find(g=>g.areaName === this._room.currentState.areaName)
                  , _ = ((d == null ? void 0 : d.step) || 7.5) * 30;
                this._room.updateCurrentState({
                    speed: _,
                    attitude: c
                }),
                this._room.pathManager.currentAttitude = c,
                this._room._userAvatar && (this._room._userAvatar.motionType = c)
            }
            this._room.sceneManager.getCurrentShaderMode() !== ECurrentShaderMode.pano && !this._room.isPano && o.playerState.camera && this._room.camera.setCameraPose(o.playerState.camera)
        }
        if (o != null && o.renderInfo && this._room.camera.handleRenderInfo(o),
        n.actionType !== void 0) {
            const {actionType: u, code: c, echoMsg: h, traceId: f} = n;
            u === Actions.Echo && c === Codes.Success && this._room.networkController.rtcp.heartbeat.pong(h, f),
            c !== Codes.Success ? eventsManager.remove(f, c) : [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(u) && eventsManager.remove(f, c, n)
        }
    }
    handleActionResponses(e) {
        !(e != null && e.actionResponses) || e.actionResponses.length === 0 || e.actionResponses.forEach(t=>{
            if (t.actionType == null)
                return;
            const {pointType: r, extra: n, actionType: o, traceId: a, code: s, msg: l} = t;
            o === Actions.GetNeighborPoints ? eventsManager.remove(a, s, t.nps) : o === Actions.GetUserWithAvatar ? eventsManager.remove(a, s, t.userWithAvatarList) : eventsManager.remove(a, s, l),
            r === PointType.Path && o === Actions.Clicking && (this._room.moveToExtra = decodeURIComponent(n))
        }
        )
    }
    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
        })
    }
}