package com.bayer.edam.excelimport;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
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;

/**
 * Quick and dirty: Reads the files that made it into eDAM from a CSV list and determines their IDs from the import file.
 * 
 * @author gexce
 *
 */
public class ImportVerifier {

	private static Logger log = Logger.getLogger(ImportVerifier.class);
	private static String logfilePath = "C:\\Temp\\Migration CS - PhotoGallery\\ImportVerifier.log";

	private static String importFilePath = "C:\\Temp\\Migration CS - SQL Server\\export_2017-08-23_incl_Releases.csv";
	private static String migrationListingPath = "C:\\Temp\\Migration CS - PhotoGallery\\Frederic - Toolbox Migration DB export - COMPLETE.csv";

	private CsvParserSettings parserSettings = new CsvParserSettings();
	private List<String[]> importFile;
	private List<String[]> migrationListing;

	private HashSet<Integer> assetIDs = new HashSet<Integer>();
	private HashSet<String> filenames = new HashSet<String>();

	public ImportVerifier() throws IOException {
		parserSettings.getFormat().setLineSeparator("\r\n");
		parserSettings.getFormat().setDelimiter(';');
		parserSettings.getFormat().setCharToEscapeQuoteEscaping('"');
		parserSettings.setHeaderExtractionEnabled(false);
		CsvParser parser = new CsvParser(parserSettings);
		importFile = parser.parseAll(new File(importFilePath));
		migrationListing = parser.parseAll(new File(migrationListingPath));

		long lineNo = 0;
		for (String[] line : migrationListing) {
			lineNo++;
			String guid = line[0];
			String filename = line[1];
			
			if (filenames.contains(filename)) {
				log.warn("File '" + filename + "' has already been processed. Skipping line " + lineNo);
				continue;
			}
			
			filenames.add(filename);
			boolean found = false;
			for (String[] importLine : importFile) {
				if (filename.equals(importLine[1])) {
					assetIDs.add(Integer.parseInt(importLine[0]));
					found = true;
				}
			}
			
			if (!found) {
				log.error("No line for file " + filename);
			}
		}
		
		log.info("Number of asset IDs: " + assetIDs.size());
		
		for (Integer assetID : assetIDs) {
			log.info(assetID);
		}
	}

	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.INFO);

			new ImportVerifier();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
