package com.jens.rhasspy.shoppinglist;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;

public class Product
{
	static ArrayList<Product> productCache = null;
	
	long id;
	String name;
	String synonyms;
	StoreType storeType;
	
	public long getId()
	{
		return id;
	}
	public void setId(long id)
	{
		this.id = id;
	}
	
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	
	public String getSynonyms()
	{
		return synonyms;
	}
	public void setSynonyms(String synonyms)
	{
		this.synonyms = synonyms;
	}
	
	public static ArrayList<Product> readAllProducts()
	{
		if(productCache == null)
		{
			try
			{				
				Connection conn = DatabaseHandler.getInstance().getConnection();
				
				if(conn == null)
					Start.exitWithError(Settings.languageBlock.get("dbCouldNotConnect"));
				
				PreparedStatement preparedStmt = null;
		
				String query = "SELECT * FROM products";
				
				preparedStmt = conn.prepareStatement(query);
				
				Miscellaneous.logEvent(preparedStmt.toString(), 5);
				
		        ResultSet res = preparedStmt.executeQuery();
		        
				productCache = new ArrayList<Product>();
				
		        while (res.next())
		        {
		        	Product p = new Product();
		        	
		        	p.setId(res.getLong("id"));
		        	p.setName(res.getString("name"));
		        	p.setSynonyms(res.getString("synonyms"));
		        	
		        	StoreType st = StoreType.getById(res.getLong("storeTypeId"));
		        	p.setStoreType(st);
		        	
		        	productCache.add(p);
		        }
		        
		        res.close();
				preparedStmt.close();
			}
			catch(Exception e)
			{
				Start.exitWithError(Settings.languageBlock.get("dbCouldNotConnect"));
			}
		}
	        		
        return productCache;
	}
	
	@Override
	public boolean equals(Object obj)
	{
		return ((Product)obj).getName().equalsIgnoreCase(getName());
	}
	
	public static Product getByName(String productName)
	{
		for(Product p : readAllProducts())
		{
			if(p.getName().equalsIgnoreCase(productName))
				return p;
			else if(p.getName().equalsIgnoreCase(productName.replace("-", " ")))
				return p;
		}
		
		return null;
	}
	
	@Override
	public String toString()
	{
		return getName();
	}
	
	public static Product getById(long id)
	{
		for(Product p : readAllProducts())
		{
			if(p.getId() == id)
				return p;
		}
		
		return null;
	}
	public StoreType getStoreType()
	{
		return storeType;
	}
	public void setStoreType(StoreType storeType)
	{
		this.storeType = storeType;
	}
	
	public boolean create()
	{
		String query = "INSERT INTO nodes (name, synonyms, storeTypeId) VALUES (?, ?, ?)";
		Connection conn = DatabaseHandler.getInstance().getConnection();
		PreparedStatement preparedStmt = null;
		try
		{
			preparedStmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
		    
			preparedStmt.setString(1, this.getName());
			
			if(this.getSynonyms() == null)
				preparedStmt.setNull(2, Types.VARCHAR);
			else
				preparedStmt.setString(2, getSynonyms());
			
			preparedStmt.setLong(3, getStoreType().getId());
		    
		    preparedStmt.executeUpdate();
		    ResultSet rs = preparedStmt.getGeneratedKeys();
		    if (rs.next())
		    {
		    	this.setId(rs.getInt(1));
		    	Miscellaneous.logEvent("INSERT-ID: " + String.valueOf(this.getId()), 5);

				rs.close();
				preparedStmt.close();
		    	
		    	Miscellaneous.logEvent("Product has been successfully created.", 2);
		
		    	return true;
		    }
		    else
		    {
		    	rs.close();
		    	String error = "Insert new product failed.";
		    	Miscellaneous.logEvent(error, 1);
		    }
		}
		catch (SQLException e)
		{
			Miscellaneous.logEvent(Diverse.getStackTraceAsString(e), 1);
		}
		finally
		{
			try
			{
				if(preparedStmt != null && !preparedStmt.isClosed())
					preparedStmt.close();
			}
			catch (SQLException e)
			{
			}
		}
	      
		return false;
	}
}