//
// Created by Иван_Архипов on 24.11.2017.
//

#ifndef LOTRO_DAT_LIBRARY_TEXTSUBFILE_H
#define LOTRO_DAT_LIBRARY_TEXTSUBFILE_H

#include "SubFile.h"
#include "SubfileData.h"
#include "BinaryData.h"

#include <vector>
#include <unordered_map>

namespace LOTRO_DAT {
    struct TextFragment {
        long long fragment_id;
        std::u16string text;
        std::string args;

        bool operator < (const TextFragment &other) const {
            return fragment_id < other.fragment_id;
        }
    };

    class TextSubFile : public SubFile {
    public:
        TextSubFile() = delete;
        explicit TextSubFile(const TextSubFile &other) = delete;
        SubFile &operator =(const TextSubFile &other) = delete;


        TextSubFile(SubFile preinit_file);

        FILE_TYPE FileType() const override;

        std::string Extension() const override;

        SubfileData PrepareForExport(const BinaryData &file_data) override;

        BinaryData MakeForImport(const BinaryData &old_data, const SubfileData &data) override;

    private:
        std::vector<TextFragment> patch_fragments_;

        std::vector<std::u16string> text_pieces_;
        std::vector<long long> argument_references_;
        std::vector<std::vector<BinaryData>> argument_strings_;

        static BinaryData buffer_;

    private:
        void MakePieces(const BinaryData &data, long long &offset);

        void MakeArgumentReferences(const BinaryData &data, long long &offset);

        void MakeArgumentStrings(const BinaryData &data, long long &offset);

        void ParsePatchFragments(const SubfileData &data);

        BinaryData BuildPieces(const BinaryData &data, const TextFragment &new_data, long long &offset);

        BinaryData BuildArgumentReferences(const BinaryData &data, const TextFragment &new_data, long long &offset);

        BinaryData BuildArgumentStrings(const BinaryData &data, const TextFragment &new_data, long long &offset);

        BinaryData GetPieceData(const BinaryData &data, long long &offset) const;

        BinaryData GetArgumentReferenceData(const BinaryData &data, long long &offset) const;

        BinaryData GetArgumentStringsData(const BinaryData &data, long long &offset) const;
    };
};


#endif //LOTRO_DAT_LIBRARY_TEXTSUBFILE_H
