#ifndef NETWORK_SWITCH_MULTICAST_TABLE_H
#define NETWORK_SWITCH_MULTICAST_TABLE_H

#include <cstdint>
#include <vector>
#include <optional>
#include <algorithm>

#include "core/types.h"
#include "network/packet.h"

namespace dofs {

struct McTree {
        std::vector<PortId> child_ports;
        std::optional<PortId> parent_port;
        uint8_t weight{1};
        uint8_t tier{0};
        uint16_t tree_id{0};
        uint8_t epoch{0};
};

class MulticastTable {
public:
        MulticastTable();

        bool add_tree(std::size_t group_id, uint16_t tree_id);
        bool delete_tree(std::size_t group_id, uint16_t tree_id);

        bool add_child_port(std::size_t group_id, uint16_t tree_id, PortId out_port);
        bool delete_child_port(std::size_t group_id, uint16_t tree_id, PortId out_port);

        bool set_parent(std::size_t group_id, uint16_t tree_id, PortId parent);
        bool set_weight(std::size_t group_id, uint16_t tree_id, uint8_t w);
        bool set_epoch(std::size_t group_id, uint16_t tree_id, uint8_t epoch);

        const std::vector<McTree> *trees_of(std::size_t group_id) const;
        std::size_t group_count() const noexcept;

        // Legacy: return ports from tree_id=0 for each group bit
        std::vector<PortId> get_port_list(PacketGroups groups) const;

private:
        static bool insert_sorted_unique(std::vector<PortId> &vec, PortId v);
        static bool erase_sorted(std::vector<PortId> &vec, PortId v);

        std::vector<std::vector<McTree>> _groups;
};

} // namespace dofs

#endif // NETWORK_SWITCH_MULTICAST_TABLE_H
