/*
 * Author:Wasim Ansari
 * Date:02-FEB-15
 * Request ID:D14IKAT004 (PO Wizard)
 */
package ibase.webitm.servlet.wms;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.ITMException;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.zip.GZIPOutputStream;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;;


public class PorderTableServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	InitialContext ctx = null;
    
    public PorderTableServlet() 
    {
    	 super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost( request, response );
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		System.out.println("XXXXXXXXXXXXXXXXXXXXXX[ ItemParentChange Started ]XXXXXXXXXXXXXXXXXXXX");

		ServletOutputStream outputStream = null;
		HttpSession sess = null;
		
		String sql = "";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String color,size,dimension,itemCode = "";
		
		String dColor,dSize,dDim = "";
		
		HashMap dataMap = new HashMap();
		ArrayList sizeList = new ArrayList();
		ArrayList colorList = new ArrayList();
		ArrayList dimensionList = new ArrayList();
		
		
		try 
		{
			StringBuffer valueXmlString = new StringBuffer("<Root>\r\n");
			valueXmlString.append("<PRODUCT_SET selected = 'N'>\r\n");
			String itmcode = request.getParameter("ITEMCODE"); 
			String objName = (request.getParameter("OBJ_NAME")==null) ? "":request.getParameter("OBJ_NAME").trim();
			
			System.out.println("ITEMCODE = ["+itmcode+"] OBJ_NAME=["+objName+"]");
			
			sess = request.getSession();
			System.out.println( "sess.getId() :["+sess.getId()+"]" );
			
			if(ctx == null)
			{
				ctx = getInitialContext();  
			}
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			
			//TH SET
			valueXmlString.append("<TH_SET selected = 'N'>\r\n");
			sql = " SELECT DISTINCT PHY_ATTRIB_1 AS PSIZE FROM ITEM WHERE ITEM_PARNT = ?  order by PHY_ATTRIB_1 ";
 			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itmcode);
			rs = pstmt.executeQuery();
			valueXmlString.append("<SET><![CDATA[").append("Color").append("]]></SET>\r\n");
			valueXmlString.append("<SET><![CDATA[").append("Dimension").append("]]></SET>\r\n");
			while (rs.next())
			{
				
				dSize = checkNullAndTrim(rs.getString(1));
			/*	valueXmlString.append("<ITM_CODE domID='"+ num +"' selected = 'N'>\r\n");

				valueXmlString.append("<fieldId><![CDATA[").append(fieldId).append("]]></fieldId>\r\n");
				valueXmlString.append("<fieldValue><![CDATA[").append(fieldValue).append("]]></fieldValue>\r\n");
				valueXmlString.append("</ITM_CODE>\r\n");*/
				sizeList.add(dSize);
				valueXmlString.append("<SET><![CDATA[").append(dSize).append("]]></SET>\r\n");
			}
			
			if (rs != null) 
			{					
				rs.close();
				rs = null;
			}
			if (pstmt != null ) 
			{					
				pstmt.close();
				pstmt = null;
			}
			
			
			valueXmlString.append("</TH_SET>\r\n");
			//TH SET
			sql = " SELECT DISTINCT PHY_ATTRIB_2 AS color FROM ITEM WHERE ITEM_PARNT = ?  order by PHY_ATTRIB_2 ";
 			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itmcode);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				dColor = checkNullAndTrim(rs.getString(1));
				colorList.add(dColor);
				
			}
			if (rs != null) 
			{					
				rs.close();
				rs = null;
			}
			if (pstmt != null ) 
			{					
				pstmt.close();
				pstmt = null;
			}
			
			sql = " SELECT DISTINCT PHY_ATTRIB_3 AS DIM FROM ITEM WHERE ITEM_PARNT = ?  order by PHY_ATTRIB_3 ";
 			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itmcode);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				dDim = checkNullAndTrim(rs.getString(1));
				dimensionList.add(dDim);
				
			}
			if (rs != null) 
			{					
				rs.close();
				rs = null;
			}
			if (pstmt != null ) 
			{					
				pstmt.close();
				pstmt = null;
			}
			
			
			
			
			
			
			
			//sql = "select item_code,descr from item where item_parnt = ? ";
			sql = " SELECT PHY_ATTRIB_2 COLOR, PHY_ATTRIB_3 ITEMDIMENSION,ITEM_CODE,PHY_ATTRIB_1 SIZE1"
					+" FROM ITEM WHERE item_parnt = ? "
					+" GROUP BY ITEM_CODE,PHY_ATTRIB_2,PHY_ATTRIB_1,PHY_ATTRIB_3 ORDER BY PHY_ATTRIB_2,PHY_ATTRIB_3,PHY_ATTRIB_1 ";
 			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itmcode);
			rs = pstmt.executeQuery();
			
			int num = 1;
			while (rs.next())
			{
				color = checkNullAndTrim(rs.getString("COLOR"));
				dimension = checkNullAndTrim(rs.getString("ITEMDIMENSION"));
				size = checkNullAndTrim(rs.getString("SIZE1"));
				itemCode = checkNullAndTrim(rs.getString("ITEM_CODE"));
			/*	valueXmlString.append("<ITM_CODE domID='"+ num +"' selected = 'N'>\r\n");

				valueXmlString.append("<fieldId><![CDATA[").append(fieldId).append("]]></fieldId>\r\n");
				valueXmlString.append("<fieldValue><![CDATA[").append(fieldValue).append("]]></fieldValue>\r\n");
				valueXmlString.append("</ITM_CODE>\r\n");*/
				dataMap.put(color+":"+dimension+":"+size, itemCode);
				
				
			
			}
			
			if (rs != null) 
			{					
				rs.close();
				rs = null;
			}
			if (pstmt != null ) 
			{					
				pstmt.close();
				pstmt = null;
			}
			
			valueXmlString.append("<RECORDS>\r\n");
			int dimlistlen = dimensionList.size();
			int colorlen = colorList.size();
			int sizelen = sizeList.size();
			String key = "";
			StringBuffer temStrBuffer = null;
			boolean isItemExist = false;
			for(int i=0;i<dimlistlen;i++)
			{
				for(int j=0;j<colorlen;j++)
				{
					temStrBuffer = new StringBuffer("");
					isItemExist = false;
					temStrBuffer.append("<tr>\r\n");
					temStrBuffer.append("<td><![CDATA[").append(colorList.get(j)).append("]]></td>\r\n");
					temStrBuffer.append("<td><![CDATA[").append(dimensionList.get(i)).append("]]></td>\r\n");
				
					for(int k=0;k<sizelen;k++)
					{
						
						key = colorList.get(j) + ":"+ dimensionList.get(i) + ":"+ sizeList.get(k);
						
						System.out.println("Current Key["+key+"]");
						
						temStrBuffer.append("<td>\r\n");
						if(dataMap.containsKey(key))
						{
							
							isItemExist =true;
							temStrBuffer.append("<![CDATA[").append(dataMap.get(key)).append("]]>\r\n");
							
						}
						else
						{
							temStrBuffer.append("<![CDATA[").append("X").append("]]>\r\n");
							
						}
						temStrBuffer.append("</td>\r\n");
						
					}
					temStrBuffer.append("</tr>\r\n");
					
					/***********************************************************/
					
					sql = " select rate from pricelist where item_code = '0000000068' "
							+"and price_list in (select price_list from supplier where supp_code = 'SUP0000001')";
		 			
					pstmt = conn.prepareStatement(sql);
					
					rs = pstmt.executeQuery();
					
					temStrBuffer.append("<rate>\r\n");
					while (rs.next())
					{
						String rate1 = checkNullAndTrim(rs.getString("rate"));
						temStrBuffer.append("<![CDATA[").append(rate1).append("]]>\r\n");
					}
					
					temStrBuffer.append("</rate>\r\n");
					
					if (rs != null) 
					{					
						rs.close();
						rs = null;
					}
					if (pstmt != null ) 
					{					
						pstmt.close();
						pstmt = null;
					}
					
					
					/************************************************************/
					
					if(isItemExist)
					{
						valueXmlString.append(temStrBuffer.toString());
					}
				}
				
			}
			
			
			valueXmlString.append("</RECORDS>\r\n");
			
			valueXmlString.append("</PRODUCT_SET>\r\n");
			valueXmlString.append("</Root>");
			
            System.out.println("returnXMLString = ["+valueXmlString.toString()+"]");
            
            response.setContentType("text/xml");
            
            if(CommonConstants.CONTENT_ENCODING != null && CommonConstants.CONTENT_ENCODING.equalsIgnoreCase("gzip"))
			{
				response.setHeader("Content-Encoding", "gzip");
				GZIPOutputStream gzOutStream = new GZIPOutputStream(response.getOutputStream());
				gzOutStream.write(valueXmlString.toString().getBytes());
				gzOutStream.flush();
				gzOutStream.close();
			}
			else
			{
				response.setHeader("Content-Encoding", "");
				OutputStream outStream = response.getOutputStream();
				outStream.write(valueXmlString.toString().getBytes());
				outStream.flush();
				outStream.close();
			}
			System.out.println("****** ItemParentChange End Successfully ***********");
            
		}
		catch (Exception e)
		{
			e.printStackTrace();
	        System.out.println("Exception :ProdWizItemChangeServlet: doPost :==>");
	        try 
	        {
				throw new ITMException(e);
			} 
	        catch (ITMException e1) 
	        {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		finally 
		{
			try 
			{
				if (rs != null) 
				{					
					rs.close();
					rs = null;
				}
				if (pstmt != null ) 
				{					
					pstmt.close();
					pstmt = null;
				}
				if (conn != null && !conn.isClosed()) 
				{					
					conn.close();
					conn = null;
				}
			} 
			catch (Exception e) 
			{
				System.out.println("Exception :ProdWizItemChangeServlet :==>\n"+ e.getMessage());
				try {
					throw new ITMException(e);
				} catch (ITMException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}

	}
	
	protected InitialContext getInitialContext()throws ITMException
	{
		InitialContext ctx = null;
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :[ItemParentChange] :getInitialContext :==>");
			throw itme;
		}
		catch(Exception e)
		{
			System.out.println("Exception :[ItemParentChange] :getInitialContext :==>");
			throw new ITMException(e);
		}
		return ctx;
	}
	
	private String checkNullAndTrim(String input)
	{
		if (input==null)
		{
			input="";
		}
		return input.trim();
	}

}
