#include "ap_validate_inc.h"
#include "ap_result.h"
#include "ap_validator.h"

int check_set(vector< RESULT>& results, WORKUNIT& wu, int& canonicalid,
	double& granted_credit, bool& retry)
{
        ap_checkset checkset;
	try {
	        checkset=ap_checkset(results,wu);
	} catch (ValidatorError &v_err) {
		log_messages.printf(SCHED_MSG_LOG::MSG_CRITICAL,
                                    "[AP_CHECK_SET] %s\n", v_err.what().c_str()
		);
		retry = true;
		return -1;
	} 
	if (checkset.has_canonical_result) {
		granted_credit = checkset.granted_credit;
		canonicalid = checkset.canonical_id;
		retry = false;


#ifdef TEST
		//std::cout << "It has canonical_result and granted_credit is "
		//	<< granted_credit << std::endl;
		std::cout << std::endl;
		checkset.stats.print();
		std::cout << std::endl;
#endif
	}
	return 0;
}

int check_pair(RESULT& new_result, RESULT & canonical, bool& retry)
{
	retry = true;
	ap_checkpair checkpair;

	try {
	  checkpair=ap_checkpair(new_result,canonical);
	} catch (ValidatorError &v_err) {
		log_messages.printf(SCHED_MSG_LOG::MSG_CRITICAL,
                                    "[AP_CHECK_PAIR] %s\n ", v_err.what().c_str()
		);
		retry = true;
		return -1;
	}

	if (checkpair.has_weakly_similar)
		retry = false;

	return 0;
}


// #ifdef TEST
#if 0
// test program:
// ap_validate file1 ... filen
//

int main(int argc, char** argv)
{
	int i, retval;
	bool retry;

	vector< RESULT> results;
	RESULT r;
	WORKUNIT wu;
	double credit;
	int canonicalid = 0;

	wu.min_quorum = 1;

	for (i = 1; i < argc; i++) {
		memset(&r, 0, sizeof(r));
		r.claimed_credit = 10 * i;
		r.id = i;
		sprintf(r.xml_doc_out,
			"<file_info>\n"
			"    <name>%s</name>\n"
			"</file_info>\n", argv[i]);
		results.push_back(r);
	}

	retval = check_set(results, wu, canonicalid, credit, retry);
	if (retval) {
		printf("error: %d\n", retval);
	}

	for (i = 0; i < results.size(); i++) {
		printf("validate_state of %s is %d , ", argv[i+1], results[i].validate_state);
		printf("granted_credit = %f\n", results[i].granted_credit);
	}

	if (canonicalid) {
		printf("canonical result is %d; credit is %f\n", canonicalid, credit);
	} else {
		printf("no canonical result found\n");
	}
}

#endif
