/*
 * Created on Mar 6, 2007
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package ibase.webitm.ejb.mfg;

import java.util.*;
import ibase.webitm.utility.GenericUtility;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.dis.DistCommon;

/**
 * @author ashah
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MfgCommon {
	public String chkStkOpt(String siteCode, String itemCode, Connection conn)  throws ITMException, Exception
	{
		String stkOpt = "", sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			sql = " SELECT CASE WHEN STK_OPT IS NULL THEN 'N' ELSE STK_OPT END FROM SITEITEM " 
				+ " WHERE ITEM_CODE = ? AND SITE_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			System.out.println("Sql ::: " + sql);
			System.out.println("Setting params -- itemCode :: " + itemCode + " siteCode :: " + siteCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				stkOpt = rs.getString(1);
				System.out.println("stkOpt in chkStkOpt ::: " + stkOpt);
			}
			pstmt.close();
			rs.close();
			//if (stkOpt.equalsIgnoreCase("N") || stkOpt == null ||  )
			if (stkOpt == null || "N".equalsIgnoreCase(stkOpt) || stkOpt.trim().length() == 0 )
			{
				sql = "SELECT CASE WHEN STK_OPT IS NULL THEN '0' ELSE STK_OPT END FROM ITEM WHERE ITEM_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					stkOpt = rs.getString(1);
				}
				pstmt.close();
				rs.close();
			}
		}
		catch(Exception e)
		{throw new ITMException(e);}
		System.out.println("stkOpt in chkStkOpt :: " + stkOpt);
		return stkOpt;
		
	}

	public String chkQcReqd(String siteCode, String itemCode, Connection conn)  throws ITMException, Exception 
	{
		String qcReqd = "", sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			System.out.println("In chkQcReqd :--: siteCode :: " + siteCode + " itemCode :: " + itemCode);
			sql = " SELECT CASE WHEN QC_REQD IS NULL THEN 'N' ELSE QC_REQD END FROM SITEITEM " 
				+ " WHERE ITEM_CODE = ? AND SITE_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				qcReqd = rs.getString(1);
			}
			pstmt.close();
			rs.close();
			if (qcReqd.equalsIgnoreCase("N") || qcReqd == null)
			{
				sql = "SELECT CASE WHEN QC_REQD IS NULL THEN 'N' ELSE QC_REQD END FROM ITEM WHERE ITEM_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					qcReqd = rs.getString(1);
				}
				pstmt.close();
				rs.close();
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return qcReqd;
	}
	
	public String chkAutoQcReqd(String siteCode, String itemCode, Connection conn)   throws ITMException, Exception
	{
		String autoQcReqd = "", sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			System.out.println("In chkAutoQcReqd :--: siteCode :: " + siteCode + " itemCode :: " + itemCode);
			sql = " SELECT CASE WHEN AUTO_REQC IS NULL THEN 'Y' ELSE AUTO_REQC END FROM SITEITEM " 
				+ " WHERE ITEM_CODE = ? AND SITE_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				autoQcReqd = rs.getString(1);
			}
			pstmt.close();
			rs.close();
			if (autoQcReqd.equalsIgnoreCase("N") || autoQcReqd == null)
			{
				sql = "SELECT CASE WHEN AUTO_REQC IS NULL THEN 'Y' ELSE AUTO_REQC END FROM ITEM WHERE ITEM_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					autoQcReqd = rs.getString(1);
				}
				pstmt.close();
				rs.close();
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return autoQcReqd;
	}

	private Timestamp getTimestampFormat(String stDate)   throws ITMException, Exception
	{
		Timestamp tsDate = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
			try {
				System.out.println(" Before converting into Timestamp ::: " + stDate);
				Object date = null;
				SimpleDateFormat sdfApp = new SimpleDateFormat(genericUtility.getApplDateFormat());
				date = sdfApp.parse(stDate);
				SimpleDateFormat sdfDB = new SimpleDateFormat(genericUtility.getDBDateFormat());
				tsDate = java.sql.Timestamp.valueOf(sdfDB.format(date).toString() + " 00:00:00.0");
			} catch (Exception e) {
				throw new ITMException(e);
			}
			System.out.println(" After converted into Timestamp ::: " + tsDate);
			return tsDate;
	}
	
	public String getEnvMfg(String prdCode, String varName, Connection conn)  throws ITMException, Exception
	  {
			String varValue = "";
			String sql = "";
			ResultSet rs = null;
			PreparedStatement pstmt = null;
			try
			{
				System.out.println("In getEnvMfg ");
				sql= "SELECT VAR_VALUE FROM MFGPARM WHERE PRD_CODE = ? AND VAR_NAME = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, prdCode);
				pstmt.setString(2, varName);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					varValue =rs.getString(1);
					System.out.println("In getEnvMfg varValue..." + varValue);
				}
				else
				{
					System.out.println("No record found for PRD_CODE ='"+prdCode+"' AND VAR_NAME ='"+varName+"'");
					varValue = "NULLFOUND";
				}
				pstmt.close();
				rs.close();
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
			return varValue;
	  }
	//  13/07/13 manoharan new method to get mfg_date,exp_date as ArrayList
	public ArrayList getMfgExpDate(String tranId, String calledFrom, java.sql.Timestamp completionDate, Connection conn)   throws ITMException, Exception
	{
		ArrayList mfgExpList = new ArrayList<java.sql.Timestamp>();
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String 	logicParm = "", logicTtype = "", mfgMethod = "", siteCode = "", tranType = "", itemCode = "", expiryMethod= "";
		String lotNo = "" , bomCode = "" , sql = "", lotNoIssue = "", tempCode = "", tempString = "", itemSer	= "", mfgDateOn = "", trackShekfLife = "";
		java.sql.Timestamp tranDate = null, mfgDate = null, expDate = null, relDate = null, complDate = null;
		Date tranDate1 = null;
		int count = 0;
		double shelfLife = 0;
		DistCommon distCommon = new DistCommon();

		try
		{

			sql= "SELECT SITE_CODE,	BOM_CODE, ORDER_TYPE,LOT_NO__ISSUE,REL_DATE, "
				+ " ITEM_CODE,LOT_NO,ORD_DATE,MFG_DATE__START,EXP_DATE "
				+ " FROM WORKORDER WHERE WORK_ORDER = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				siteCode = rs.getString("SITE_CODE");
				bomCode = rs.getString("BOM_CODE");
				tranType = rs.getString("ORDER_TYPE");
				lotNoIssue = rs.getString("LOT_NO__ISSUE");
				relDate = rs.getTimestamp("REL_DATE");
				
				itemCode = rs.getString("ITEM_CODE");
				lotNo = rs.getString("LOT_NO");
				tranDate = rs.getTimestamp("ORD_DATE");
				mfgDate = rs.getTimestamp("MFG_DATE__START");
				expDate = rs.getTimestamp("EXP_DATE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			tranType = tranType.trim();
			if (relDate == null)
			{
				relDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
				SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
				relDate = java.sql.Timestamp.valueOf(sdt.format(relDate) + " 00:00:00.000");
			}

			sql= "SELECT ITEM_SER,	SHELF_LIFE,	MFG_DATE_ON,	TRACK_SHELF_LIFE"
				+ " FROM ITEM WHERE ITEM_CODE = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				itemSer = rs.getString("ITEM_SER");
				shelfLife = rs.getDouble("SHELF_LIFE");
				mfgDateOn = rs.getString("MFG_DATE_ON");
				trackShekfLife = rs.getString("TRACK_SHELF_LIFE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql= "SELECT COUNT(1) FROM ITEM_LOT_INFO "
				+ " WHERE ITEM_CODE = ? "
				+ " AND LOT_NO = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, lotNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				count = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if (count > 0 )
			{
				sql= "SELECT MFG_DATE, EXP_DATE FROM ITEM_LOT_INFO "
					+ " WHERE ITEM_CODE = ? "
					+ " AND LOT_NO = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				pstmt.setString(2, lotNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					mfgDate = rs.getTimestamp("MFG_DATE");
					expDate = rs.getTimestamp("EXP_DATE");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				mfgExpList.add(mfgDate);
				mfgExpList.add(expDate);
				return mfgExpList;
			}
			sql= "SELECT COUNT(1) FROM STOCK "
				+ " WHERE ITEM_CODE = ? "
				+ " AND SITE_CODE = ? "
				+ " AND LOT_NO = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			pstmt.setString(3, lotNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				count = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if (count > 0 )
			{
				sql= "SELECT MIN(MFG_DATE) AS MFG_DATE, MIN(EXP_DATE) AS EXP_DATE FROM STOCK "
				+ " WHERE ITEM_CODE = ? "
				+ " AND SITE_CODE = ? "
				+ " AND LOT_NO = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				pstmt.setString(2, siteCode);
				pstmt.setString(3, lotNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					mfgDate = rs.getTimestamp("MFG_DATE");
					expDate = rs.getTimestamp("EXP_DATE");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				mfgExpList.add(mfgDate);
				mfgExpList.add(expDate);
				return mfgExpList;
			}

			if (mfgDateOn ==  null)
			{
				sql= "SELECT MFG_DATE_ON FROM ITEMSER WHERE ITEM_SER = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemSer);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					mfgDateOn = rs.getString("MFG_DATE_ON");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
			}
			if (mfgDateOn == null)
			{
				mfgDateOn = "S";
			}
			if("R".equals(calledFrom))
			{
				complDate =  completionDate;
			}
			if (lotNo == null || lotNo.trim().length() == 0 )
			{
				lotNo = " ";
			}
			
			
			logicParm = getEnvMfg("999999", "MFG_DATE_LOGIC", conn);

			if (logicParm == null || "NULLFOUND".equals(logicParm))
			{
				throw new Exception("VTMFGDL~t MFG_DATE_LOGIC");
			}
			else if ("U".equals(logicParm))
			{
				logicTtype =  getEnvMfg("999999", "MFG_DATE_LOGIC_TYPE", conn);
			
				if (logicTtype == null || "NULLFOUND".equals(logicTtype) )
				{
					 throw new Exception("VTMFGDL~t MFG_DATE_LOGIC_TYPE");
				}
				else if ("D".equals(logicTtype))
				{
					mfgMethod =  getEnvMfg("999999", "MFG_DATE_METHOD", conn);
					
					if (mfgMethod == null || "NULLFOUND".equals(mfgMethod) )
					{
						throw new Exception("VTMFGDL~t MFG_DATE_METHOD");
					}
					else
					{
						sql = "SELECT " +  mfgMethod.trim() 
							+ "('" + siteCode + "',to_date('" + (new SimpleDateFormat("yyyy-MM-dd").format(tranDate)) + "','yyyy-mm-dd')" 
							+ ",'" + tranType + "','" + itemCode +  "','" + lotNo 
							+ "','" + bomCode + "') from dual"  ;

						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							mfgDate = rs.getTimestamp(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
					}
				}
				/*else if ("B".equals(logicTtype))
				{
					//not specified
				}*/
			}
			else if ("S".equals(logicParm))
			{
				// 24-12-04 manoharan other than 'F' - Fresh lot no can be isse lot no
				if ("F".equals(tranType))
				{
					
					if (mfgDate != null)
					{
						if ("C".equals(mfgDateOn))
						{
							if ("W".equals(calledFrom))
							{
								mfgDate = null;
							}
							else
							{
								mfgDate = complDate;
							}
						}
						else if ("S".equals(mfgDateOn))
						{
							mfgDate = relDate;
						}
					}
				}
				else if (!"F".equals(tranType))
				{
					if (lotNoIssue == null || lotNoIssue.trim().length() == 0)
					{
						lotNoIssue = " ";
					}

					if (mfgDate == null)
					{
						String lotNoIssueIN = "";
						String arrStr[] = lotNoIssue.split(",");
						int len =arrStr.length;
						for(int i =0;i<len;i++)
						{
							lotNoIssueIN = lotNoIssueIN + "'"+arrStr[i]+"',";
						}
						lotNoIssueIN =lotNoIssueIN.substring(0,lotNoIssueIN.length()-1);

						sql = "	SELECT MIN(MFG_DATE) FROM STOCK "
							+ " WHERE  ITEM_CODE IN (  SELECT DISTINCT ITEM_CODE "
							+ " FROM BOMDET WHERE BOM_CODE = ? "
							+ " AND CONSIDER_LOT_NO__ISSUE = 'Y' ) " 
							+ "	AND LOT_NO IN (" + lotNoIssueIN + ") ";

						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,bomCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							mfgDate = rs.getTimestamp(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
					}
					else
					{
						if (mfgDate == null)
						{
							if ("C".equals(mfgDateOn))
							{
								if ("W".equals(calledFrom))
								{
									mfgDate = null;
								}
								else
								{
									mfgDate = complDate;
								}
							}
							else if ("S".equals(mfgDateOn))
							{
								mfgDate = relDate;
							}
						}
					}
				}
			}
			System.out.println("Manufacturing before  tranType [" + tranType + "] mfgDate [" + mfgDate +"] relDate [" + relDate + "] mfgDateOn [" + mfgDateOn + "] complDate [" + complDate +"] lotNoIssue [" + lotNoIssue + "]");
			
			if ("S".equals(logicParm) && "S".equals(mfgDateOn) && mfgDate == null)
			{
				mfgDate = relDate;
			}
			System.out.println("Manufacturing after  tranType [" + tranType + "] mfgDate [" + mfgDate +"] relDate [" + relDate + "] mfgDateOn [" + mfgDateOn + "] complDate [" + complDate +"] lotNoIssue [" + lotNoIssue + "]");			
			logicParm = getEnvMfg("999999", "EXP_DATE_LOGIC", conn);

			if (logicParm == null || "NULLFOUND".equals(logicParm))
			{
				throw new Exception("VTMFGDL~t EXP_DATE_LOGIC");
			}
			else if ("U".equals(logicParm))
			{
				logicTtype = getEnvMfg("999999", "EXP_DATE_LOGIC_TYPE", conn);
				if (logicTtype == null || "NULLFOUND".equals(logicTtype) )
				{
					 throw new Exception("VTMFGDL~t EXP_DATE_LOGIC_TYPE");
				}
				else if ("D".equals(logicTtype))
				{
					expiryMethod =  getEnvMfg("999999", "EXP_DATE_METHOD", conn);
					
					if (expiryMethod == null || "NULLFOUND".equals(expiryMethod) )
					{
						throw new Exception("VTMFGDL~t EXP_DATE_METHOD");
					}
					else
					{
						sql = "select " +  expiryMethod.trim() + "('" + tranId + "','" + lotNo 
							+ "',to_date('" + (new SimpleDateFormat("yyyy-MM-dd").format(mfgDate)) + "','yyyy-mm-dd')" + ",'W','"+ itemCode  +"') from dual";
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							expDate = rs.getTimestamp(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
					}
				}
				/*else if ("B".equals(logicTtype))
				{
					//not define yet
				}*/
					
			}
			else if ("S".equals(logicParm))
			{
				if ("F".equals(tranType))
				{
					if (mfgDate == null)
					{
						if ("C".equals(mfgDateOn))
						{
							if ("W".equals(calledFrom))
							{
								mfgDate = null;
							}
							else
							{
								mfgDate = complDate;
							}
						}
						else if ("S".equals(mfgDateOn))
						{
							mfgDate = relDate;
						}
					}
					
					if (expDate== null)
					{
						if (!"Y".equals(trackShekfLife))
						{
							expDate = null;
						}
						else
						{
							expDate = distCommon.CalcExpiry(mfgDate,shelfLife);

						sql = "SELECT LAST_DAY(?) FROM DUAL ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1,expDate);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							expDate = rs.getTimestamp(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						}
					}
				}	
				else if (!"F".equals(tranType))
				{

					String lotNoIssueIN = "";
					String arrStr[] = lotNoIssue.split(",");
					int len =arrStr.length;
					for(int i =0;i<len;i++)
					{
						lotNoIssueIN = lotNoIssueIN + "'"+arrStr[i]+"',";
					}
					lotNoIssueIN =lotNoIssueIN.substring(0,lotNoIssueIN.length()-1);

					sql = "	SELECT MIN(EXP_DATE) FROM STOCK "
						+ " WHERE  ITEM_CODE IN (  SELECT DISTINCT ITEM_CODE "
						+ " FROM BOMDET WHERE BOM_CODE = ? "
						+ " AND CONSIDER_LOT_NO__ISSUE = 'Y' ) " 
						+ "	AND LOT_NO IN (" + lotNoIssueIN + ") ";

					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,bomCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						expDate = rs.getTimestamp(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					if (expDate == null)
					{
						if (mfgDate == null)
						{
							if ("C".equals(mfgDateOn))
							{
								if ("W".equals(calledFrom))
								{
									mfgDate = null;
								}
								else
								{
									mfgDate = complDate;
								}
							}
							else if ("S".equals(mfgDateOn))
							{
								mfgDate = relDate;
							}
						}
					
						if (!"Y".equals(trackShekfLife))
						{
							expDate = null;
						}
						else
						{
							expDate = distCommon.CalcExpiry(mfgDate,shelfLife);
							sql = "SELECT LAST_DAY(?) FROM DUAL ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setTimestamp(1,expDate);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								expDate = rs.getTimestamp(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
					}
				}
			}

			mfgExpList.add(mfgDate);
			mfgExpList.add(expDate);
		
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return mfgExpList;
	}
	  
}
