import {WebSocketEvent} from "./WebSocketEvent";
import {Buffer} from "buffer";

export class WebSocketPayload {
    set event(value: WebSocketEvent) {
        this._event = value;
    }


    set data(value: any | undefined) {
        this._data = value;
    }

    private _event: WebSocketEvent;
    private _data: any | undefined;


    get event(): WebSocketEvent {
        return this._event;
    }



    get data(): any | undefined {
        return this._data;
    }

    constructor(event: WebSocketEvent, data?: any) {
        this._event = event;
        this._data = data;
    }

    public static parseFromBase64Json(json: any): WebSocketPayload | null {
        //json = (typeof window != 'undefined') ? atob(json).toString() : Buffer.from(json, "base64").toString("utf-8");
        json = Buffer.from(json, "base64").toString("utf-8");
        let rawPayload: { event: string, data: any };
        try {
            rawPayload = JSON.parse(json);
        } catch (e) {
            return null;
        }

        let wsEvent = WebSocketEvent[<keyof typeof WebSocketEvent>rawPayload.event];

        return new WebSocketPayload(wsEvent, rawPayload.data);
    }

    /**
     * Returns the payload as base64 encoded json string
     */
    public toString(): string {
        let json = JSON.stringify({"event": this._event, data: this._data});

        json = ((typeof window != 'undefined') ? btoa(json) : Buffer.from(json).toString("base64"));
        return json;
    }
}