/*
    PIP - Platform Independent Primitives
    Compress class using zlib
    Andrey Bychkov work.a.b@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "picompress.h"

#include "pitranslator.h"
#ifdef PIP_COMPRESS
#  ifdef ESP_PLATFORM
#	include "esp32/rom/miniz.h"
#	define compress2  mz_compress2
#	define Z_OK       MZ_OK
#	define uncompress mz_uncompress
#  else
#	include <zlib.h>
#  endif
#endif


PIByteArray piCompress(const PIByteArray & ba, int level) {
#ifdef PIP_COMPRESS
	PIByteArray zba;
	zba.resize(ba.size() + 128);
	int ret  = 0;
	ulong sz = zba.size();
	ret      = compress2(zba.data(), &sz, ba.data(), ba.size(), level);
	if (ret != Z_OK) {
		piCout << "[PICompress]"
			   << "Error: invalid input or not enought memory"_tr("PICompress");
		return ba;
	}
	zba.resize(sz);
	zba << ullong(ba.size());
	return zba;
#else
	piCout << "[PICompress]"
		   << "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library"_tr("PICompress");
#endif
	return ba;
}


PIByteArray piDecompress(const PIByteArray & zba) {
#ifdef PIP_COMPRESS
	ullong sz = 0;
	if (zba.size() < sizeof(ullong)) {
		piCout << "[PICompress]"
			   << "Error: invalid input"_tr("PICompress");
		return zba;
	}
	PIByteArray ba(zba.data(zba.size() - sizeof(ullong)), sizeof(ullong));
	ba >> sz;
	ba.resize(sz);
	int ret = 0;
	ulong s = sz;
	ret     = uncompress(ba.data(), &s, zba.data(), zba.size() - sizeof(ullong));
	if (ret != Z_OK) {
		piCout << "[PICompress]"
			   << "Error: invalid input or not enought memory"_tr("PICompress");
		return zba;
	}
	return ba;
#else
	piCout << "[PICompress]"
		   << "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library"_tr("PICompress");
#endif
	return zba;
}
