package com.jens.rhasspy.shoppinglist;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class Start
{
	public static void main(String[] args)
	{
		float amount = 0;
		String unitName = null;
		String productName = null;
		String action = null;
		String filePath = null;
		
		List<String> argsList  = new ArrayList<String>();  
	    List<String> optsList  = new ArrayList<String>();
	    List<String> doubleOptsList  = new ArrayList<String>();
	    for (int i=0; i < args.length; i++)
	    {
    		switch (args[i].charAt(0))
	        {
		        case '-':
		            if (args[i].charAt(1) == '-')
		            {
		                int len = 0;
		                String argstring = args[i].toString();
		                len = argstring.length();
//		                System.out.println("Found double dash with command " + argstring.substring(2, len) );
		                String argName = argstring.substring(2, len);
		                doubleOptsList.add(argName);
		                if(argName.equalsIgnoreCase("shoppingAmount"))
		                	amount = Float.parseFloat(args[i+1].replace("\"", ""));
		                else if(argName.equalsIgnoreCase("shoppingUnit"))
		                	unitName = args[i+1].replace("\"", "");
		                else if(argName.equalsIgnoreCase("shoppingProduct"))
			                productName = args[i+1].replace("\"", "");
		                else if(argName.equalsIgnoreCase("action"))
		                	action = args[i+1].replace("\"", "");
		                else if(argName.equalsIgnoreCase("filePath"))
		                	filePath = args[i+1].replace("\"", "");
		            }
		            else
		            {
//		                 System.out.println("Found dash with command " + args[i].charAt(1) + " and value " + args[i+1] );   
		                 i= i+1;
		                 optsList.add(args[i]);      
		            }           
		         break;         
		         default:            
//		         System.out.println("Add a default arg." );
		         argsList.add(args[i]);
		         break;
	         }     
	     }
		
    	Settings.readSettings();
    	
	    if(action == null)
	    {
	    	System.out.println(Settings.languageBlock.get("noActionDefined"));
	    }
	    else
	    {
	    	
		    switch(action)
		    {
			    case "addToList":
				    if(!StringUtils.isEmpty(productName))
				    {
				    	ShoppingList list = ShoppingList.getMostRecentList();
				    	
				    	Unit u = Unit.getByName(unitName);
				    	Product p = Product.getByName(productName);
				    	
			    		ShoppingListEntry entry = new ShoppingListEntry();
			    		entry.setParentList(list);
			    		entry.setProduct(p);
			    		entry.setAmount(amount);
			    		entry.setUnit(u);
			    		
			    		if(amount > 0 && (u == null || u.isDummy))
			    			entry.setUnit(Unit.getPieceUnit());
			    		
				    	if(list == null)
				    		exitWithError(Settings.languageBlock.get("couldNotCreateList"));
				    	
				    	if(p == null)
				    		exitWithError(Settings.languageBlock.get("productNotFound") + " " + entry.toString());
				    	
			    		if(entry.create())
			    		{
			    			DatabaseHandler.getInstance().disconnect();
			    			System.exit(0);
			    		}
			    		else
			    			exitWithError(Settings.languageBlock.get("couldNotAddProdToList") + " " + entry.toString());
				    }
				    else
				    	System.out.println(Settings.languageBlock.get("noProdSpecified"));
				    break;
			    case "removeFromList":
				    if(!StringUtils.isEmpty(productName))
				    {
				    	ShoppingList list = ShoppingList.getMostRecentList();
				    	Product p = Product.getByName(productName);
				    	Unit u = Unit.getByName(unitName);
				    	
			    		ShoppingListEntry entry = new ShoppingListEntry();
			    		entry.setParentList(list);
			    		entry.setProduct(p);
			    		entry.setAmount(amount);
			    		entry.setUnit(u);
			    		
			    		if(amount > 0 && (u == null || u.isDummy))
			    			entry.setUnit(Unit.getPieceUnit());
			    		
				    	if(list == null)
				    		exitWithError(Settings.languageBlock.get("couldNotCreateList"));
				    	
				    	if(p == null)
				    		exitWithError(Settings.languageBlock.get("productNotFound") + " " + entry.toString());
			    		
			    		if(entry.delete())
			    		{
			    			DatabaseHandler.getInstance().disconnect();
			    			System.exit(0);
			    		}
			    		else
			    			exitWithError(Settings.languageBlock.get("couldNotRemoveProdFromList") + " " + entry.toString());
				    	
			    		// If it wasn't on the list - why care?
		    			DatabaseHandler.getInstance().disconnect();
		    			System.exit(0);
				    }
				    else
				    	System.out.println(Settings.languageBlock.get("noProdSpecified"));
				    break;
			    case "sendList":
			    	if(ShoppingList.getMostRecentList().sendViaEmail())
			    	{
//				    	System.out.println("Liste wurde verschickt.");
				    	DatabaseHandler.getInstance().disconnect();
				    	System.exit(0);
			    	}
			    	else
				    	System.out.println(Settings.languageBlock.get("couldNotSendList"));
			    	break;
			    case "resetList":
			    	if(ShoppingList.createNewList() != null)
			    	{
//				    	System.out.println("Neue Liste erstellt");
				    	DatabaseHandler.getInstance().disconnect();
				    	System.exit(0);
			    	}
			    	else
				    	System.out.println(Settings.languageBlock.get("couldNotCreateNewList"));
			    	break;
			    case "importProducts":
			    	File importFile = new File(filePath);
			    	importFile(importFile);
			    	break;
		    }
	    }
	    
	    exitWithError(null);
	}
	
	static void exitWithError(String errorText)
	{
		if(!StringUtils.isEmpty(errorText))
		{
			System.out.println(errorText);
			Miscellaneous.logEvent("Exiting with error: " + errorText, 1);
		}
		else
			Miscellaneous.logEvent("Exiting with empty error.", 1);
		
		DatabaseHandler.getInstance().disconnect();	    
		System.exit(1);
	}
	
	static boolean importFile(File importFile)
	{
		try
		{
			if(!importFile.exists())
	    		exitWithError("File does not exist.");
	    	
	    	if(!importFile.canRead())
	    		exitWithError("Cannot read file.");
	    	
	    	String fileContent = Miscellaneous.readFile(importFile).trim();
			
			if(StringUtils.isEmpty(fileContent))
				exitWithError("File is empty.");
			
			int errorCounter = 0;
			
			outerLoop:
			for(String line : fileContent.split(Diverse.lineSeparator))
			{
				String[] synonyms = line.split(":");
				String product = synonyms[synonyms.length -1];
				
				for(Product existingProduct : Product.readAllProducts())
				{
					if(existingProduct.getName().equalsIgnoreCase(product))
						continue outerLoop;
				}
	
				Product newProduct = new Product();
				newProduct.setName(product);
				newProduct.setStoreType(StoreType.readAllStoreTypes().get(0));
				
				if(synonyms.length > 1)
				{
					String syns = synonyms[0].substring(1, synonyms[0].length()-1);
					syns = syns.replace("|", ";");
					newProduct.setSynonyms(syns);
				}
				
				if(!newProduct.create())
				{
					Miscellaneous.logEvent("Failed to import product " + newProduct.getName(), 1);
					errorCounter++;
				}
			}
			
			if(errorCounter > 0)
				System.out.println("Import complete with " + String.valueOf(errorCounter) + ".");
			else
				System.out.println("Import complete without errors.");
			
			return true;
		}
		catch(Exception e)
		{
			
		}
		
		return false;
	}
}