#include "chain-vdr.h"
#include "logger-vdr.h"
#include "setup.h"
#include "menuburn.h"
#include "proctools/format.h"
#include "proctools/logger.h"
#include <memory>
#include <vdr/config.h>
#include <sys/time.h>
#include <sys/resource.h>

namespace vdr_burn
{

	using namespace std;
	using proctools::chain;
	using proctools::logger;
	using proctools::format;

	chain_vdr::chain_vdr(const string& name, job& job_):
			chain(name),
#if VDRVERSNUM >= 10300
			cThread("burn: subprocess watcher"),
#endif
			m_job(job_),
			m_progress(0),
			m_burning(false)
	{
		const string templ = "/.vdr-burn.XXXXXX";
		m_paths.temp = create_temp_path(BurnParameters.TempPath + templ);
		m_paths.data = create_temp_path(BurnParameters.DataPath + templ);
		job_.set_paths(m_paths);
		logger_vdr::set_logfile(m_job.get_log_path());
	}

	chain_vdr::~chain_vdr()
	{
		stop();
		execute(format("rm -rf {0}") % m_paths.temp);
		execute(format("rm -rf {0}") % m_paths.data);
	}

	void chain_vdr::stop(void)
	{
		chain::stop();
		Cancel(3);
	}

	void chain_vdr::add_process(proctools::process* proc)
	{
		proc->set_workdir(m_paths.data);
		chain::add_process(proc);
	}

	string chain_vdr::create_temp_path(const string& templ)
	{
		char *path = new char[templ.length() + 1];
		strcpy(path, templ.c_str());
		mkdtemp(path);

		string result( path );
		delete[] path;
		return result;
	}

	void chain_vdr::Action(void)
	{
#if VDRVERSNUM < 10300
		logger::info(format("subprocess watcher thread started (pid={0})")
					 % getpid());
		setpriority(PRIO_PROCESS, 0, 19);
#else
		SetPriority(19);
#endif

		run();

#if VDRVERSNUM < 10300
		logger::info(format("subprocess watcher thread stopped (pid={0})")
					 % getpid());
#endif
	}
};
