// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/DOCKING/COMMON/structurePreparer.h>
#include <BALL/DATATYPE/options.h>
#include <BALL/DOCKING/IMGDOCK/IMGDock.h>
#include <BALL/SCORING/COMMON/gridBasedScoring.h>
#include <BALL/DOCKING/COMMON/constraints.h>
#include "version.h"

using namespace BALL;
using namespace std;

int main(int argc, char* argv[])
{
	CommandlineParser parpars("IMGDock", "Iterative Multi-Greedy Docking", VERSION, String(__DATE__), "Docking");
	parpars.registerMandatoryInputFile("rec", "receptor pdb-file");
	parpars.registerMandatoryInputFile("rl", "reference-ligand");
	parpars.registerOptionalInputFile("pocket", "configuration file");
	parpars.registerMandatoryInputFile("i", "compounds to be docked");
	parpars.registerMandatoryOutputFile("o", "output file for docked compounds");
	parpars.registerOptionalOutputFile("write_ini", "write ini-file w/ default parameters (and don't do anything else)");
	parpars.registerFlag("rm", "remove input file when finished");
	parpars.registerMandatoryInputFile("grd", "ScoreGrid file");
	String man = "IMGDock docks compounds into the binding pocket of a receptor using an iterative multi-greedy approach.\nAs input we need:\n\n\
    * a file containing a protonated protein in pdb-format\n\
    * a file containing a reference ligand. This reference ligand should be located in the binding pocket. Supported formats are mol2, sdf or drf (DockResultFile, xml-based).\n\
    * a score-grid file generated by GridBuilder. This grid must have been precalculated for the same receptor and reference ligand as those that are to be used here.\n\
    * a file containing the compounds that are to be docked. Supported formats are mol2, sdf or drf (DockResultFile, xml-based). These molecules must have been assigned 3D coordinates (e.g. by Ligand3DGenerator) and should have been checked for errors using LigCheck.\n\nOutput of this tool is a file containing all compounds docked into the binding pocket, with a property-tag named 'score' indicating the score obtained for each compound.\n\nTip: If you want to parallelize docking, use LigandFileSplitter to separate your input file containing the compounds to be docked into several batches, dock each batch with this tool and merge the output files with DockResultMerger.";
	parpars.setToolManual(man);
	parpars.setSupportedFormats("rec","pdb");
	parpars.setSupportedFormats("rl",MolFileFactory::getSupportedFormats());
	parpars.setSupportedFormats("pocket","ini");
	parpars.setSupportedFormats("grd","grd.gz,grd,bngrd,bngrd.gz");
	parpars.setSupportedFormats("i",MolFileFactory::getSupportedFormats());
	parpars.setSupportedFormats("o","mol2,sdf,drf");
	parpars.setSupportedFormats("write_ini","ini");
	Options default_options;
	ScoringFunction::getDefaultOptions(default_options);
	IMGDock::getDefaultOptions(default_options);
	parpars.registerAdvancedParameters(default_options);
	parpars.setSupportedFormats(ScoringFunction::SUBCATEGORY_NAME, "filename", "ini");
	parpars.parse(argc, argv);

	String default_inifile = parpars.get("write_ini");
	if (default_inifile != CommandlineParser::NOT_FOUND)
	{
		// if ini-file already exists, read its entries first
		list<Constraint*> clist;
		if (ifstream(default_inifile.c_str()))
		{
			DockingAlgorithm::readOptionFile(default_inifile, default_options, clist);
		}
		Options* scoring_options = default_options.getSubcategory(ScoringFunction::SUBCATEGORY_NAME);

		scoring_options->setDefault("scoring_type", "GridedMM");
		scoring_options->setDefault("scoregrid_resolution", 0.5);
		scoring_options->setDefault("atom_types", "C, Cl, F, H, I, N, O, P, S");
		scoring_options->setDefault("nonbonded_cutoff_precalculation", scoring_options->get("nonbonded_cutoff"));
		scoring_options->set("nonbonded_cutoff", 3.0);
		DockingAlgorithm::writeOptionFile(parpars.get("write_ini"), default_options, clist);
		Log << "Ini-file w/ default values has been written to file '"<<default_inifile<<"'. Goodbye!"<<endl;
		return 0;
	}

	Log.setMinLevel(cout, 10);

	GenericMolFile* ref_ligand_file = MolFileFactory::open(parpars.get("rl"));

	//Molecule* ref_ligand = ref_ligand_file->read();
	System* ref_ligand = new System();
	ref_ligand->insert(*ref_ligand_file->read());
	ref_ligand_file->close();
	delete ref_ligand_file;

	Options option;
	parpars.copyAdvancedParametersToOptions(option);
	list<Constraint*> constraints;
	if (parpars.get("pocket") != CommandlineParser::NOT_FOUND)
	{
		DockingAlgorithm::readOptionFile(parpars.get("pocket"), option, constraints, ref_ligand);
	}
	Options* option_category = option.getSubcategory(ScoringFunction::SUBCATEGORY_NAME);
	if (!option_category) option_category = &option;
	String scoring_type = "GridedMM";

	// Make sure to use grid-based version of resp. scoring function
	if (scoring_type == "MM" || scoring_type == "GridedMM")
	{
		option_category->set("scoring_type", "GridedMM");
		scoring_type = "GridedMM";
	}
	else if (scoring_type == "PLP" || scoring_type == "GridedPLP")
	{
		option_category->set("scoring_type", "GridedPLP");
		scoring_type = "GridedPLP";
	}
	else
	{
		cerr << "[Error:] Scoring function '" << scoring_type << "' unknown/unsupported!" << endl;
		return 1;
	}

	String grid_file = parpars.get("grd");

	// make sure to use reduced cutoff if using grid-based scoring and *no* ini-file
	if (scoring_type.hasPrefix("Grided"))
	{
		option_category->set("nonbonded_cutoff", 3);
	}

	String par_file = option_category->get("filename");
	if (par_file == "")
	{
		par_file="Amber/amber96-docking.ini";
		option_category->set("filename", "Amber/amber96-docking.ini");
	}
	StructurePreparer* sp;
	if (scoring_type.hasSubstring("PLP"))
	{
		sp = new StructurePreparer("PLP");
	}
	else
	{
		sp = new StructurePreparer;
	}
	sp->prepare(ref_ligand, par_file);

	System receptor;
	GenericMolFile* input = MolFileFactory::open(parpars.get("rec"));
	if (!input)
	{
		cerr<<"Format of receptor-file not supported!"<<endl;
		return 1;
	}
	*input >> receptor;
	sp->prepare(&receptor, par_file);
	delete input;

	IMGDock docker(receptor, *ref_ligand, option);
	GridBasedScoring* gbs = dynamic_cast<GridBasedScoring*>(docker.getScoringFunction());
	ScoringFunction* sf = docker.getScoringFunction();
	for (list < Constraint* > ::iterator it = constraints.begin(); it != constraints.end(); it++)
	{
		sf->constraints.push_back(*it);
		(*it)->setScoringFunction(sf);
	}

	Log.level(10)<<endl<<"-----------------------------------------"<<endl;
	Log.level(10)<<"Scores will be calculated as : "<<sf->getEquation()<<endl;
	Log.level(10)<<"-----------------------------------------"<<endl<<endl;

	if (gbs != NULL)
	{
		gbs->replaceGridSetFromFile(grid_file);
	}

	sf->update();
	sf->updateScore();
	Log.level(10)<<"====== Reference ligand ============"<<endl;
	sf->printResult();

	/// dock entire sd-/mol2-file:
	double threshold = option.setDefaultReal("output_score_threshold", 1e100);

	docker.processMultiMoleculeFile(parpars.get("i"), parpars.get("o"), threshold);

	delete sp;
	delete ref_ligand;
	if (parpars.has("rm"))
	{
		File::remove(parpars.get("i"));
	}
	return 0;
}
