/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2022  SteamWar.de-Serverteam
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.network.packets;

import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;

import java.io.*;

@EqualsAndHashCode
public abstract class NetworkPacket implements Serializable {

    private static final long serialVersionUID = -3168992457669156473L;
    private transient MetaInfos metaInfos;

    public MetaInfos getMetaInfos() {
        return metaInfos;
    }

    @SneakyThrows
    public byte[] serialize() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);
        oos.flush();
        return baos.toByteArray();
    }

    public static void handle(byte[] data) {
        PacketHandler.handlePacket(deserialize(data));
    }

    public static void handle(MetaInfos metaInfos, byte[] data) {
        NetworkPacket networkPacket = deserialize(data);
        networkPacket.metaInfos = metaInfos;
        PacketHandler.handlePacket(networkPacket);
    }

    @SneakyThrows
    public static NetworkPacket deserialize(byte[] data) {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (NetworkPacket) ois.readObject();
    }
}
