package com.prime.sony.ecommerce.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BatchInfo;
import com.sforce.async.BulkConnection;
import com.sforce.async.ContentType;
import com.sforce.async.JobInfo;
import com.sforce.async.OperationEnum;

public class SFBulkUtils {

	private static final Logger log = LoggerFactory.getLogger(SFBulkUtils.class);

	/**
	 * Create a new job using the Bulk API.
	 * 
	 * @param sobjectType The object type being loaded, such as "Account"
	 * @param connection  BulkConnection used to create the new job.
	 * @return The JobInfo for the new job.
	 * @throws AsyncApiException
	 */
	public static JobInfo createJob(String sobjectType, BulkConnection connection) throws AsyncApiException {
		log.info("==>SFBulkUtils.createJob()");
		JobInfo job = new JobInfo();
		job.setObject(sobjectType);
		job.setOperation(OperationEnum.upsert);
		job.setExternalIdFieldName("Name");
		job.setContentType(ContentType.CSV);
		job = connection.createJob(job);
		log.info("<==SFBulkUtils.createJob()");
		return job;
	}

	/**
	 * Create a batch by uploading the contents of the file. This closes the output
	 * stream.
	 * 
	 * @param tmpOut     The output stream used to write the CSV data for a single
	 *                   batch.
	 * @param tmpFile    The file associated with the above stream.
	 * @param batchInfos The batch info for the newly created batch is added to this
	 *                   list.
	 * @param connection The BulkConnection used to create the new batch.
	 * @param jobInfo    The JobInfo associated with the new batch.
	 */
	public static void createBatch(FileOutputStream tmpOut, File tmpFile, List<BatchInfo> batchInfos,
			BulkConnection connection, JobInfo jobInfo) throws IOException, AsyncApiException {
		log.info("==>SFBulkUtils.createBatch()");
		tmpOut.flush();
		tmpOut.close();
		FileInputStream tmpInputStream = new FileInputStream(tmpFile);
		try {
			BatchInfo batchInfo = connection.createBatchFromStream(jobInfo, tmpInputStream);
			// System.out.println(batchInfo);
			batchInfos.add(batchInfo);

		} finally {
			tmpInputStream.close();
		}
		log.info("<==SFBulkUtils.createBatch()");
	}

}
