/* Copyright (C) 2014-2021 m-privacy GmbH. All Rights Reserved.
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This software 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <rfb/LogWriter.h>
#include "PrintDialog.h"
#include "printing.h"

#ifdef WIN32
#include <winsock2.h>
#include <windows.h>
#include "parameters.h"
#include "pdfprinter.h"
#endif


using namespace rdr;
using namespace rfb;

namespace printing {
	static rfb::LogWriter vlog("printing");
	PrintDialog* prin_win = NULL;
	THREAD_ID mptimer_thread_id;

	void print_pdf_file(char* pdf_file) {
		vlog.debug("print_pdf_file(%s)", pdf_file);
#ifdef WIN32
		int print_with_windows_dialog = adobePrintDialog ? 0 : 1;
		if (adobePrintDialog) {
			if (!adobe_print_pdf(pdf_file)) {
				vlog.error("%s: failed to print with Adobe Acrobat Reader. Falling back to default Windows print dialog", __func__);
				print_with_windows_dialog = 1;
			}
		}
		if (print_with_windows_dialog) {
			windows_print_pdf(pdf_file);
		}
		vlog.debug("printed");
		if (remove(pdf_file))
			vlog.error("Error: could not delete %s", pdf_file);
		else
			vlog.debug("Deleted: %s", pdf_file);
#else
		if (!prin_win)
			prin_win = new PrintDialog((char*)"TightGate Pro Drucken");

		prin_win->new_job(pdf_file);
#endif
	}

	THREAD_FUNC one_time_thread(void* pdf_file) {
#ifdef WIN32
		vlog.debug("one_time_thread(%s) %lu created", (char*) pdf_file, GetCurrentThreadId());
#else
#if defined(__APPLE__)
		vlog.debug("one_time_thread(%s) %u created", (char*) pdf_file, gettid());
#else
		vlog.debug("one_time_thread(%s) %lu created", (char*) pdf_file, gettid());
#endif
#endif
		print_pdf_file((char*) pdf_file);
		free(pdf_file);
		vlog.debug("one_time_thread finishes");
		THREAD_EXIT(THREAD_NULL);
	}


	void print_pdf_thread(char* pdf_file) {
		vlog.debug("print_pdf_thread(%s) creates a printing thread now.", pdf_file);
		THREAD_CREATE(one_time_thread, mptimer_thread_id, (void*)strdup(pdf_file));
		THREAD_SET_NAME(mptimer_thread_id, "tg-printPDF");
	}

}
