/**
 * @(#)file    PuSupplierBiz.java
 * @(#)author  이성민
 * @(#)version 1.0
 * @(#)date    2014.06.25
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 * All rights reserved.
 * This software is the proprietary information of udapsoft Inc.
 */
package kr.co.udapsoft.ebid.buyer.supplier.outside.biz;



import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.sql.WAFSQLException;
import kr.co.hsnc.common.sql.persistent.Persistent;
import kr.co.hsnc.common.sql.persistent.PersistentImpl;
import kr.co.hsnc.common.sql.search.Search;
import kr.co.hsnc.common.sql.search.SearchImpl;
import kr.co.hsnc.common.sql.util.RowSetUtility;
import kr.co.hsnc.common.util.ValueObject;
import kr.co.udapsoft.common.sender.MessageSend;

import com.udapsoft.waf.common.util.ClobUtils;
import com.udapsoft.waf.common.util.StringUtils;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;






public class QuotSupplierEmailSmsSaveBiz extends Biz {

	public QuotSupplierEmailSmsSaveBiz(HandlerStorage storage) {
		super(storage);
	}

	/* (non-Javadoc)
	 * @see kr.co.hwenc.system.Biz#doBiz()
	 */
	public void doBiz() throws Exception {

		
		
		
		if(storage.compareEvent("FORM_EMAIL_UPDATE"))
		{
			saveData();
		}
		else if(storage.compareEvent("FORM_EMAIL_TEST"))
		{
			String mailtitle = getContent().get("TITLE");
     		//StringBuffer mailtitlein = new StringBuffer();
     		StringBuffer mailContent = new StringBuffer();
     		String content = getContent().get("SEND_EMAIL");
     		
            mailContent.append(content);
            MessageSend messageSend = new MessageSend(storage);   //mailtitle.toString() mailtitlein.toString()
            messageSend.sendEmail(storage.getUser().get("USER_EMAIL"), "partner@sgc.co.kr", mailtitle, mailtitle, mailContent);
            storage.setSuccess(true);
		}
		if(storage.compareEvent("FORM_SMS_UPDATE"))
		{
			smsSaveData();
		}
		else if(storage.compareEvent("FORM_SMS_TEST"))
		{
			String content = getSmsContent().get("SEND_SMS");
			MessageSend messageSend = new MessageSend(storage);
			messageSend.sendSMS(StringUtils.replace(storage.getUser().get("USER_PCS"),"-",""),"", "99999", content);
		}
	}
	
	 public ValueObject getContent() throws Exception {

	        Search search = new SearchImpl();
	        ValueObject valueObject = null;
	        StringBuffer sqlstr = new StringBuffer();
	        try {

	            sqlstr.append( " SELECT  *                                            \n");
	            sqlstr.append("  FROM    SUPP_EMAIL                                 \n");
	            sqlstr.append("  WHERE JOB_DIV = 'Q'                                 \n");

	            search.setStatement(sqlstr);
	            valueObject = RowSetUtility.getValueObject(search.execute().getRow(0));
	            valueObject.set("SEND_EMAIL",readClob(valueObject.getObject("SEND_EMAIL")));        
	        }
	        catch(WAFSQLException se) {
	        	super.doException(se);
	        	this.storage.setSuccess(false);
	        	this.storage.setMessage(se.getMessage());
	        	storage.setDetailMessage(se);
	        }
	        finally {

	            if( valueObject == null ) valueObject = new ValueObject();
	            return valueObject;
	        }
	    }
	
	private void saveData() throws Exception{

		WAFLogger.debug("=================================================");
        boolean success = false;
        
        conn.begin();
        try 
        {
        	Connection con = conn.getConnection();
            success = updateInfo(con, params);
            super.storage.setSuccess(success);
            
        } catch (Exception e) {
			super.doException(e);
			super.storage.setDetailMessage(e);
			super.storage.setMessage(e.getMessage());
			super.storage.setSuccess(false);
			super.conn.setRollback();
		} finally {
			conn.end();
		} 
	}
	
	
	
	/**
     * 회사정보 저장
     * @param params
     * @return
     * @throws Exception
     */
    private boolean updateInfo(Connection con, ValueObject params) throws Exception
    {
        
        StringBuffer sqlstr = new StringBuffer();
        Persistent persistent = new PersistentImpl(con);
        
        
        try{
        	
        	sqlstr.append("UPDATE SUPP_EMAIL     	        \n");
        	sqlstr.append("   SET UPD_DATE = SYSDATE				\n");
        	sqlstr.append("     , UPD_BY = ?					\n");
        	sqlstr.append("     , TITLE = ?					\n");
        	sqlstr.append(" WHERE JOB_DIV = 'Q'				\n");
        	
        	 persistent.setStatement(sqlstr.toString());
             persistent.addParameter(storage.getUser().get("acct_id"));
             persistent.addParameter(params.get("p_title"));
             
             persistent.execute();
        	
        	
        	ClobUtils.setClob(con, "SUPP_EMAIL", "SEND_EMAIL", " WHERE JOB_DIV = 'Q'", params.get("email"));
            
            return true;
            
            
        } catch(Exception e) {
            throw e;
            
        }
    }
    
    /**
     * Clob Object에서 데이터를 읽어 리턴한다.
     * @param object
     * @return
     * @throws Exception
     */
    private String readClob(Object object) throws Exception {

        if( object == null ) {
        
            return "";
        }

        Clob clob = (Clob)object;
    /*  -- 2006.09.14 changed by SMH  
        Reader reader = clob.getCharacterStream();

        int size = (int)clob.length();
        char[] clobData = new char[size];
        reader.read(clobData, 0, size);
        reader.close();

        StringBuffer temp = new StringBuffer(); 
        temp.append(clobData);                

        return temp.toString();
    */    
        return getClob(clob);
    }
    
    /**
     * Clob 데이터 유형을 String으로 변경하여 반환한다.
     * @param clob
     * @return
     * @throws Exception
     */
    public static String getClob(Clob clob) throws Exception{
        String strClob = "";
        Reader reader = null;
        try {
            if(clob != null){              
                reader = clob.getCharacterStream();
                char[] buffer = new char[1024];
                int length = 0;
                while( (length = reader.read(buffer)) != -1 ) {                  
                    for( int j=0; j<length; j++ ) {
                        strClob = strClob+buffer[j];
                    }
                }
            }        
        }
        finally {
            if(reader != null) reader.close();                    
        }   
        return strClob;
    }
    
    private void smsSaveData() throws Exception{

		WAFLogger.debug("=================================================");
        boolean success = false;
        
        conn.begin();
        try 
        {
        	Connection con = conn.getConnection();
            success = updateSmsInfo(con, params);
            super.storage.setSuccess(success);
            
        } catch (Exception e) {
			super.doException(e);
			super.storage.setDetailMessage(e);
			super.storage.setMessage(e.getMessage());
			super.storage.setSuccess(false);
			super.conn.setRollback();
		} finally {
			conn.end();
		} 
	}
    
    /**
     * 회사정보 저장
     * @param params
     * @return
     * @throws Exception
     */
    private boolean updateSmsInfo(Connection con, ValueObject params) throws Exception
    {
        
        StringBuffer sqlstr = new StringBuffer();
        Persistent persistent = new PersistentImpl(con);
        
        
        try{
        	
        	sqlstr.append("UPDATE SUPP_SMS     	        \n");
        	sqlstr.append("   SET UPD_DATE = SYSDATE				\n");
        	sqlstr.append("     , UPD_BY = ?					\n");
        	sqlstr.append("     , TITLE = ?					\n");
        	sqlstr.append(" WHERE JOB_DIV = 'Q'				\n");
        	
        	 persistent.setStatement(sqlstr.toString());
             persistent.addParameter(storage.getUser().get("acct_id"));
             persistent.addParameter(params.get("p_title"));
             
             persistent.execute();
        	
        	
        	ClobUtils.setClob(con, "SUPP_SMS", "SEND_SMS", " WHERE JOB_DIV = 'Q'", params.get("sms"));
            
            return true;
            
            
        } catch(Exception e) {
            throw e;
            
        }
    }
    
    public ValueObject getSmsContent() throws Exception {

        Search search = new SearchImpl();
        ValueObject valueObject = null;
        StringBuffer sqlstr = new StringBuffer();
        try {

            sqlstr.append( " SELECT  *                                            \n");
            sqlstr.append("  FROM    SUPP_SMS                                 \n");
            sqlstr.append("  WHERE JOB_DIV = 'Q'                                 \n");

            search.setStatement(sqlstr);
            valueObject = RowSetUtility.getValueObject(search.execute().getRow(0));
            valueObject.set("SEND_SMS",readClob(valueObject.getObject("SEND_SMS")));        
        }
        catch(WAFSQLException se) {
        	super.doException(se);
        	this.storage.setSuccess(false);
        	this.storage.setMessage(se.getMessage());
        	storage.setDetailMessage(se);
        }
        finally {

            if( valueObject == null ) valueObject = new ValueObject();
            return valueObject;
        }
    }
   
}