package com.bayer.edam;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;

public class ToolboxFileExporter {
	
	private static Logger log = Logger.getLogger(ToolboxFileExporter.class);
	private static String logfilePath = "C:\\Temp\\Migration CS - PhotoGallery\\export - 2017-08-28 - all logos and tags.download.log";
	
	private static String toolboxExportFilePath = "C:\\Temp\\Migration CS - PhotoGallery\\export - 2017-08-28 - all logos and tags.csv";
	
	private List<String[]> rows;
	private String baseDir = "D:\\ToolboxLogosAndTags";
	
	// Formatdatei generiert mit
	// bcp "SELECT OriginalImage FROM AssetImages WHERE AssetID=586" queryout Image.jpg -S MOVNCG -d Bayertoolbox_prod -T
	//   Geben Sie den Dateispeichertyp des Felds OriginalImage ein [varbinary(max)]: x
	//   Geben Sie die Präfixlänge des OriginalImage-Felds ein [8]: 0
	//   Geben Sie das Feldabschlusszeichen ein [none]:

	// Abruf:
	//   bcp "SELECT OriginalImage FROM AssetImages WHERE AssetID=586" queryout Image5.jpg -S MOVNCG -d Bayertoolbox_prod -T -f bcp.fmt
	
	private String command1 = "bcp \"SELECT OriginalImage FROM AssetImages WHERE AssetID=";
	private String command2 = "\" queryout \"";
	private String command3 = "\" -S MOVNCG -d Bayertoolbox_prod -T -f \"D:\\Toolbox\\bcp.fmt\" -a 16384";
	
	private File workingDir = new File(baseDir);
	
	public ToolboxFileExporter() throws Exception {
		readList();
		
		for (String[] row : rows) {
			getImage(row[0], row[1]);
		}
		
	}
	
	private void getImage(String assetId, String originalFilenname) throws Exception {
		if (new File(baseDir + File.separator + assetId).exists()) {
			log.error("File for asset " + assetId + " already present, skipping");
		}
		else {
			log.info("Download for asset " + assetId + ", OriginalFilename: '" + originalFilenname + "'");
			Process process = Runtime.getRuntime().exec(command1 + assetId + command2 + assetId + command3, null, workingDir);
			process.waitFor();
			if (0 < process.exitValue()) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String s;
				while ((s = reader.readLine()) != null) {
					log.error(s);
				}
			}
		}
	}
	
	private void readList() {
		CsvParserSettings settings = new CsvParserSettings();
	    settings.getFormat().setLineSeparator("\r\n");
	    settings.getFormat().setDelimiter(';');
	    settings.getFormat().setCharToEscapeQuoteEscaping('"');
	    settings.setHeaderExtractionEnabled(false);

	    CsvParser parser = new CsvParser(settings);

	    rows = parser.parseAll(new File(toolboxExportFilePath));
	}
	

	public static void main(String[] args) {
		try {
			Layout layout = new PatternLayout("%d{ISO8601} - %p %m%n"); // "%d{ISO8601} - %p %m%n"
			BasicConfigurator.configure(new ConsoleAppender(layout));
			BasicConfigurator.configure(new RollingFileAppender(layout, logfilePath, false));
			log.setLevel(Level.DEBUG);
			
			long startTime = System.currentTimeMillis();
			log.debug("Start: " + startTime);
			
			new ToolboxFileExporter();
			
			long endTime = System.currentTimeMillis();
			log.debug("End: " + endTime);
			log.debug("Duration: " + (endTime - startTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
