/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* writerperfect
 * Version: MPL 2.0 / LGPLv2.1+
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Major Contributor(s):
 * Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com)
 * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU Lesser General Public License Version 2.1 or later
 * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
 * applicable instead of those above.
 *
 * For further information visit http://libwpd.sourceforge.net
 */

#include <cstdio>

#include "WPWrapperWPS.hxx"

#include <librevenge/librevenge.h>
#include <libwps/libwps.h>

#include "UserOptions.hxx"

#ifndef __EMSCRIPTEN__
#  include <sys/stat.h>
#  include <sys/types.h>

#  include <map>
#  include <string>
#endif

#ifndef __EMSCRIPTEN__
namespace writerperfectWPWrapperWPS
{
////////////////////////////////////////////////////////////
// static class to create a RVNGInputStream for some data
////////////////////////////////////////////////////////////

/** internal class used to create a structrured RVNGInputStream from a list of file and their short names
 */
class FolderStream: public librevenge::RVNGInputStream
{
public:
	//! constructor
	FolderStream() : librevenge::RVNGInputStream(), m_nameToPathMap()
	{
	}

	//! destructor
	~FolderStream()
	{
	}

	//! add a file
	void addFile(std::string const &path, std::string const &shortName)
	{
		m_nameToPathMap[shortName]=path;
	}
	/**! reads numbytes data.

	 * \return a pointer to the read elements
	 */
	const unsigned char *read(unsigned long, unsigned long &)
	{
		return 0;
	}
	//! returns actual offset position
	long tell()
	{
		return 0;
	}
	/*! \brief seeks to a offset position, from actual, beginning or ending position
	 * \return 0 if ok
	 */
	int seek(long, librevenge::RVNG_SEEK_TYPE)
	{
		return 1;
	}
	//! returns true if we are at the end of the section/file
	bool isEnd()
	{
		return true;
	}

	/** returns true if the stream is ole

	 \sa returns always false*/
	bool isStructured()
	{
		return true;
	}
	/** returns the number of sub streams.

	 \sa returns always 2*/
	unsigned subStreamCount()
	{
		return unsigned(m_nameToPathMap.size());
	}
	/** returns the ith sub streams name */
	const char *subStreamName(unsigned id)
	{
		std::map<std::string, std::string>::const_iterator it=m_nameToPathMap.begin();
		for (unsigned i=0; i<id; ++i)
		{
			if (it==m_nameToPathMap.end()) return 0;
			++it;
		}
		if (it==m_nameToPathMap.end()) return 0;
		return it->first.c_str();
	}
	/** returns true if a substream with name exists */
	bool existsSubStream(const char *name)
	{
		return name && m_nameToPathMap.find(name)!= m_nameToPathMap.end();
	}
	/** return a new stream for a ole zone */
	librevenge::RVNGInputStream *getSubStreamByName(const char *name);
	/** return a new stream for a ole zone */
	librevenge::RVNGInputStream *getSubStreamById(unsigned id)
	{
		char const *name=subStreamName(id);
		if (name==0) return 0;
		return getSubStreamByName(name);
	}
private:
	/// the map short name to path
	std::map<std::string, std::string> m_nameToPathMap;
	FolderStream(const FolderStream &); // copy is not allowed
	FolderStream &operator=(const FolderStream &); // assignment is not allowed
};

librevenge::RVNGInputStream *FolderStream::getSubStreamByName(const char *name)
{
	if (m_nameToPathMap.find(name)== m_nameToPathMap.end()) return 0;
	return new librevenge::RVNGFileStream(m_nameToPathMap.find(name)->second.c_str());
}

////////////////////////////////////////////////////////////
// main functions
////////////////////////////////////////////////////////////

/* check if the file is a lotus123 file and a .fm3 file exists or
   if the file is a dos lotus file and a .fmt file exists.
   If yes, try to convert it in a structured input which can be parsed by libwps */
static shared_ptr<librevenge::RVNGInputStream> createMergeInput(char const *fName, librevenge::RVNGInputStream &input)
try
{
	shared_ptr<FolderStream> res;

	/* we do not want to compress already compressed file.
	   So check if the file is structured, is a binhex file
	 */
	if (!fName || input.isStructured()) return res;

	// first check
	std::string name(fName);
	size_t len=name.length();
	if (len<=4 || name[len-4]!='.') return res;
	std::string extension=name.substr(len-3, 2);
	if (extension!="wk" && extension!="WK")
		return res;

	// check the file header
	if (input.seek(0, librevenge::RVNG_SEEK_SET)!=0) return res;
	unsigned long numBytesRead;
	const unsigned char *data=input.read(6, numBytesRead);
	if (!data || numBytesRead!=6 || data[0]!=0 || data[1]!=0 || data[3]!=0) return res;
	bool oldFile=false;
	if (data[2]==2 && data[4]==6 && data[5]==4)
		oldFile=true;
	else if (data[2]!=0x1a || data[4]>=2 || data[5]!=0x10) return res;

	// check if the .fm3 file exists
	std::string fmName=name.substr(0, len-3);
	if (extension=="wk")
		fmName+=oldFile ? "fmt" : "fm3";
	else
		fmName+=oldFile ? "FMT" : "FM3";
	struct stat status;
	if (stat(fmName.c_str(), &status) || !S_ISREG(status.st_mode))
		return res;

	res.reset(new FolderStream());
	if (oldFile)
	{
		res->addFile(name, "WK1");
		res->addFile(fmName, "FMT");
	}
	else
	{
		res->addFile(name, "WK3");
		res->addFile(fmName, "FM3");
	}
	return res;
}
catch (...)
{
	return shared_ptr<librevenge::RVNGInputStream>();
}
}
#endif

namespace writerperfect
{
bool WPWrapperWPS::parseDocument(librevenge::RVNGInputStream &input, librevenge::RVNGSpreadsheetInterface &collector)
{
	return libwps::WPS_OK==libwps::WPSDocument::parse(&input, &collector, m_options->getPassword(), m_options->getEncoding());
}
bool WPWrapperWPS::parseDocument(librevenge::RVNGInputStream &input, librevenge::RVNGTextInterface &collector)
{
	return libwps::WPS_OK==libwps::WPSDocument::parse(&input, &collector, m_options->getPassword(), m_options->getEncoding());
}
bool WPWrapperWPS::checkInput(shared_ptr<librevenge::RVNGInputStream> &input)
{
	libwps::WPSCreator creator;
	libwps::WPSKind kind = libwps::WPS_TEXT;
	bool needEncoding;
	bool ok=false;
#ifndef __EMSCRIPTEN__
	shared_ptr<librevenge::RVNGInputStream> mergeStream=writerperfectWPWrapperWPS::createMergeInput(m_options->getInput(), *input);
	if (mergeStream &&
	        libwps::WPSDocument::isFileFormatSupported(mergeStream.get(), kind, creator, needEncoding) != libwps::WPS_CONFIDENCE_NONE)
	{
		ok=true;
		input=mergeStream;
	}
#endif
	if (!ok && libwps::WPSDocument::isFileFormatSupported(input.get(), kind, creator, needEncoding) == libwps::WPS_CONFIDENCE_NONE)
		return false;
	if (!setType(kind))
		return false;
	if (needEncoding && (!m_options || !m_options->getEncoding()))
		fprintf(stderr, "WARNING: called without encoding, try to decode with basic character set encoding.\n");
	return true;
}

bool WPWrapperWPS::setType(int kind)
{
	Type fileType;
	if (kind == libwps::WPS_TEXT)
		fileType=Text;
	else if (kind == libwps::WPS_SPREADSHEET || kind == libwps::WPS_DATABASE)
		fileType=Spreadsheet;
	else
		return false;
	if (m_fileType != Unknown)
	{
		if (m_fileType!=fileType)
			return false;
		m_type=fileType;
	}
	m_type=fileType;
	return true;
}
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
