#include "epm_handler_common.h"
#include <tc\tc_macros.h>
#include <tc\emh.h>
#include <tc\preferences.h>
#include <property\propdesc.h>
#include <epm\epm.h>
#include <epm\epm_toolkit_tc_utils.h>
#include <tccore\item.h>
#include <tccore\grmtype.h>
#include <tccore\grm.h>
#include <tccore\imantype.h>
#include <sa\am.h>
#include <sa\sa.h>
#include <tccore\aom.h>
#include <tccore\aom_prop.h>
#include <property\prop_errors.h>
#include <tccore\workspaceobject.h>
#include <qry\qry.h>
#include <bom\bom_attr.h>
#include <bom\bom.h>
#include <epm\signoff.h>
#include <pom\pom\pom.h>
#include <pom\pom\pom_errors.h>
#include <fclasses\tc_date.h>
#include <epm\cr.h>
#include <cfm\cfm.h>
#include <sa\am.h>
#include "tc/envelope.h"
#include <stdio.h>
#include "ae/dataset.h"
#include <ctype.h>
#include <string.h>
#include <string>
#include <iostream>
#include <iterator>
#include <map>
#include <vector>
#include "ce/ce.h"
#include <time.h>
#include <windows.h>  
#include <iostream>  
#include <sql.h>  
#include <sqlext.h>  
#include "string"
#include "sstream"
#include <sa/tcfile.h>
#include <tccore/aom.h>
#include <sa/tcfile_cache.h>
#include "ctime"
#include "tchar.h"

using namespace std;
extern "C" int POM_AM__set_application_bypass(logical bypass);


int bs_file_transfer(EPM_action_message_t msg)
{
	int ifail = ITK_ok, att_count;
	tag_t rootTask, *attachments;
	char *obj_type;

	EPM_ask_root_task(msg.task, &rootTask);

	EPM_ask_attachments(rootTask, EPM_target_attachment, &att_count, &attachments);
	TC_argument_list_t * arguments = msg.arguments;
	int arg_cnt = TC_number_of_arguments(arguments), status = 0;
	POM_AM__set_application_bypass(true);
	map<string, string> paras;
	
	for (auto i = 0; i<arg_cnt; i++)
	{
		char *temp_key, *temp_val;
		ITK_ask_argument_named_value(TC_next_argument(arguments), &temp_key, &temp_val);
		paras[temp_key] = temp_val;
	}
	printf("paras:");
	for(auto i=paras.begin();i!=paras.end();i++)
	{
		printf(" %s:%s ", i->first.c_str(), i->second.c_str());
	}
	printf("\n");
	for(int i=0;i<att_count;i++)
	{
		AOM_ask_value_string(attachments[i], "object_type", &obj_type);
		printf("obj_type:%s\n", obj_type);
		if (paras["type"] != obj_type)
			continue;
		int tag_cnt;
		tag_t * tags;
		AOM_ask_value_tags(attachments[i], paras["relation"].c_str(), &tag_cnt, &tags);
		for(int j=0;j<tag_cnt;j++)
		{
			int ref_cnt;
			tag_t *refs;
			AE_ask_dataset_named_refs(tags[j], &ref_cnt, &refs);
			for(int k=0;k<ref_cnt;k++)
			{
				char * name;
				IMF_ask_original_file_name2(refs[k], &name);
				ITKCALL(IMF_export_file(refs[k], (paras["path"] + name).c_str()));
			}
		}
	}
	POM_AM__set_application_bypass(false);

	return 0;
}

