package webchurch.cms.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import webchurch.push.util.Connector2;

public class CMSDAOImpl implements CMSDAO {

	@Override
	public int insert(ArrayList db, ArrayList input, String sql,
			ArrayList inputData, File file) {
		// TODO Auto-generated method stub
		int result = 0;
		System.out.println(db.get(0));
		System.out.println(db.get(1));
		System.out.println(db.get(2));
		Connection con = getConnection(db);
		String query = insertConvert(sql, input);
		System.out.println(query);
		PreparedStatement pstmt = null;
		try {
			FileInputStream fisUp = new FileInputStream(file);
			//FileInputStream fis = new FileInputStream(file);
			int b = 0;
			/*int length = 0;
			System.out.println("length count");
			while((b = fis.read())!= -1){
				length ++;
				System.out.print("."+length);
			}*/
			pstmt = con.prepareStatement(query);
			int idx = 1;
			/*for(Object in : inputData){
				
				if(in instanceof Integer){
					System.out.println("Integer : " + idx + " ------ " +in);
					pstmt.setInt(idx, (int)in);
				}else if(in instanceof String){
					System.out.println("String : " + idx + " ------ " +in);
					pstmt.setString(idx, (String)in);
				}
				idx ++;
				System.out.println(in);
			}*/
			pstmt.setString(1, (String) inputData.get(0));
			pstmt.setString(2, (String) inputData.get(1));
			pstmt.setInt(3, (Integer) inputData.get(2));
			System.out.println(idx + " ------ ");
			pstmt.setBinaryStream(4, fisUp, (Integer)inputData.get(2));
			//pstmt.setInt(5, length);
			
			result = pstmt.executeUpdate();
			con.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return result;
	}
	
	private String insertConvert(String sql, ArrayList input){
		return sql.replaceAll("input", input.toString().substring(1, input.toString().length()-1));
	}
	
	private Connection getConnection(ArrayList db){
		Connection con = null;
		try {
			System.out.println("--------------getConnection----------------------");
			System.out.println(db.get(0));
			System.out.println(db.get(1));
			System.out.println(db.get(2));
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			con = DriverManager.getConnection((String)db.get(0), (String)db.get(1), (String)db.get(2));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		//Connector2 c2 = new Connector2();
		//con =  c2.getConnection();
		return con;
	}

}
