#ifndef PGSQL_PARAMS_H
#define PGSQL_PARAMS_H

#include <vector>
#include <QString>
#include <libpq-fe.h>
#include "Pgsql_declare.h"
#include "Pgsql_oids.h"
#include <optional>

namespace Pgsql {

	class Params;

	class Param {
	public:
		Param(Params &params, int index)
			: params(params)
			, index(index)
		{}

		int getIndex() const { return index; }
	private:
		Params &params;
		int index;
	};

	class Params {
	public:
		Params();
		Params(const Params& rhs);
		Params& operator=(const Params& rhs);
		Params(Params&& rhs);
		Params& operator=(Params&& rhs);
		~Params();


        Param add(const QString &s, Oid oid=varchar_oid);
        Param add(const char *data, Oid oid=varchar_oid);
        Param add(int v, Oid oid=int4_oid);
        Param add(std::optional<std::string> s, Oid oid=varchar_oid)
		{
			return add(s ? s->c_str() : nullptr, oid);
		}

        void addParams(const Params &params);
		//void addBinary(const char *data, int length, Oid oid);
		void clear();

		bool empty() const { return m_paramTypes.empty(); }
        int size() const { return static_cast<int>(m_paramTypes.size()); }

		const Oid* types() const { return m_paramTypes.data(); }
		const char* const* values() const { return m_paramValues.data(); }
		const int* lengths() const { return m_paramLengths.data(); }
		const int* formats() const { return m_paramFormats.data(); }

	private:
		using t_paramValues = std::vector<const char *>;

		void deleteValues()
		{
			for (auto e : m_paramValues)
				delete[] e;
		}

		/* Assumes other lists already have been copied */
        void appendValues(const t_paramValues &r);

		std::vector<Oid> m_paramTypes;
		t_paramValues m_paramValues;
		std::vector<int> m_paramLengths; ///< postgresql ignores lengths for text parameters but we will it anyway for efficient copying
		std::vector<int> m_paramFormats;

		/** \brief Add a parameter to the list.
		 *
		 * The class takes ownership of data and will try to delete[] it.
		 */
		Param addText(const char *data, Oid oid=varchar_oid);
	};

} // end namespace Pgsql

#endif // PGSQL_PARAMS_H
