#include "datexportapi.h"
#include "database.h"
#include "subfile.h"

#include <string>
#include <functional>


namespace LOTRO_DAT {

struct SubfileInfo {
	int file_id;
	int size;
	int iteration;

	friend bool operator<(const SubfileInfo& info1, const SubfileInfo& info2) {
		return info1.file_id < info2.file_id;
	}
};

class DatFile;

typedef std::function<void (const SubfileInfo&)> SubfileOperation;

class DatFile {
  public:
  	DatFile(int file_handle);
  	~DatFile();
  	bool Init(const std::string& filename);
	void LoadAllFilesInfo();
  	void Deinit();

	bool Initialized() const;
	const std::string& GetFilename() const;
	size_t GetFilesNumInDatFile();

  	size_t PatchAllFilesFromDatabase(Database& db);
	void PatchFile(SubfileData file_data);
  	void PatchFile(int file_id, FILE_TYPE type, std::string path_to_file);

	FILE_TYPE GetExistingFileType(int file_id);
	void PerformOperationOnAllSubfiles(const SubfileOperation& operation);

  	int ExportFilesByType(FILE_TYPE type, Database& db);
  	int ExportFilesByType(FILE_TYPE type, std::string path_to_directory);
  	
  	void ExportFileById(int file_id, Database& db);
	void ExportFileById(int file_id, std::string target_file_path);

  private:
  	static DatExportApi api_;
  	int file_handle_;
  	bool initialized_;
	std::set<SubfileInfo> files_info_;
	std::string filename_;

  	BinaryData export_data_buf_;
};

} // namespace LOTRO_DAT