import {WebSocketEvent} from "./WebSocketEvent";

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

    set error(value: boolean) {
        this._error = value;
    }

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

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


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

    get error(): boolean {
        return this._error;
    }

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

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

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

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

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

    /**
     * Returns the payload as base64 encoded json string
     */
    public toString(): string {
        let json = JSON.stringify({"event": this._event, status: this._error, data: this._data});
        json = ((typeof window != 'undefined') ? btoa(json) : Buffer.from(json).toString("base64"));
        return json;
    }
}