#pragma once

#include "HuffmanTree.h"

#include <vector>
#include <string>
#include <optional>

class BitStream;

class HuffmanCodeLengthTable
{
public:
    void buildPrefixCodes();

    void buildCompressedLengthSequence();

    std::string dumpPrefixCodes() const;

    std::optional<HuffmanTree::Symbol> findMatch(std::size_t treeIndex, uint32_t code) const;

    const HuffmanTree& getTree() const;

    const PrefixCode& getCode(std::size_t index) const;

    std::optional<PrefixCode> getCodeForSymbol(unsigned symbol) const;

    using CompressedSequenceEntry = std::pair<unsigned, unsigned>;
    const std::vector<CompressedSequenceEntry>& getCompressedLengthSequence() const;

    const std::vector<std::size_t> getCompressedLengthCounts() const;

    std::size_t getNumCodeLengths() const;

    unsigned getCodeLength(std::size_t treeIndex) const;

    std::size_t mapToDeflateIndex(std::size_t index) const;

    void setInputLengthSequence(const std::vector<unsigned char>& sequence, bool targetDeflate = true);

    bool readNextSymbol(unsigned& buffer, BitStream* stream);

private:

    HuffmanTree mTree;
    bool mTargetDeflate{true};

    std::vector<unsigned char> mInputLengthSequence;
    std::vector<PrefixCode> mCodes;

    std::vector<CompressedSequenceEntry> mCompressedLengthSequence;
    std::vector<std::size_t> mCompressedLengthCounts;

    static constexpr unsigned DEFLATE_PERMUTATION_SIZE{19};
    static constexpr unsigned DEFLATE_PERMUTATION[DEFLATE_PERMUTATION_SIZE]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
};
