package idc.model;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

public class IdcDAO{
	
	DataSource ds;
	public static final int WRITING_PER_PAGE = 10;
	public final String reError = "중복등록_및_삭제의_우려가_있어_해당_행위는_중지되었습니다.";
	public IdcDAO(){
		try {
			Context initContext = (Context)new InitialContext().lookup("java:comp/env/");
			ds = (DataSource)initContext.lookup("jdbc/mysql");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean checkToken(HttpServletRequest request){
		int rToken = Integer.parseInt(request.getParameter("token"));
		int sToken = 0;
		if(request.getSession().getAttribute("token")!=null)
			sToken = (Integer)request.getSession().getAttribute("token");
	
		//System.out.println("세션 토큰값 : " + sToken);
		if(rToken == sToken)
			return false;
		
		return true;
	}
	
	public Connection getConn(){
		try {
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//서버 리스트 록록 조회 기능 수행
	public ArrayList<IdcServerDTO> idcServerList(String curPage){
		
		ArrayList<IdcServerDTO> list = new ArrayList<IdcServerDTO>();
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt2 = null;
		ResultSet rs = null, rs2=null;
		
		int numbering_end=WRITING_PER_PAGE * (Integer.parseInt(curPage) -1 );
		int numbering = 0;
		try {
			conn = getConn();
			String sql="SELECT COUNT(*) as a FROM serverdb";
			pstmt2=conn.prepareStatement(sql);
			rs2 = pstmt2.executeQuery();
			if(rs2.next())
				numbering = rs2.getInt("a")-numbering_end;
			sql = "SELECT server_num, server_use_status, server_code, server_cpu, server_ram, server_hdd, server_brand, server_location, ";
			sql += "server_fomat_date, server_recieve_date, server_release_date, server_note, server_disuse_date ";
			sql += "FROM serverDB ORDER BY server_num desc ";
			sql += "LIMIT ?, ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, numbering_end);
			pstmt.setInt(2, WRITING_PER_PAGE);
			
			rs = pstmt.executeQuery();
			while(rs.next()){
				int server_num = numbering--;
				String server_use_status = rs.getString("server_use_status");
				String server_code = rs.getString("server_code");
				String server_process = rs.getString("server_process");
				String server_spec = rs.getString("server_spec");
				String server_cpuname = rs.getString("server_cpuname");
				String server_ram = rs.getString("server_ram");
				String server_hdd = rs.getString("server_hdd");
				String server_brand = rs.getString("server_brand");
				String server_location = rs.getString("server_location");
				Date server_fomat_date = rs.getDate("server_fomat_date");
				Date server_recieve_date = rs.getDate("server_recieve_date");
				Date server_release_date = rs.getDate("server_release_date");
				String server_note = rs.getString("server_note");
				Date server_disuse_date = rs.getDate("server_disuse_date");				
				
				IdcServerDTO writing = new IdcServerDTO();
				writing.setServer_num(server_num);
				writing.setServer_use_status(server_use_status);
				writing.setServer_code(server_code);
				writing.setServer_process(server_process);
				writing.setServer_spec(server_spec);
				writing.setServer_cpuname(server_cpuname);
				writing.setServer_ram(server_ram);
				writing.setServer_hdd(server_hdd);
				writing.setServer_brand(server_brand);
				writing.setServer_location(server_location);
				writing.setServer_fomat_date(server_fomat_date);
				writing.setServer_recieve_date(server_recieve_date);
				writing.setServer_release_date(server_release_date);
				writing.setServer_note(server_note);
				writing.setServer_disuse_date(server_disuse_date);
				
				list.add(writing);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();				
			}
		}		
		return list;
		
	}
	
	//리스트의 페이징 처리를 위한 기능 수행
	public int idcServerPageCnt(){
		int pageCnt = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = ds.getConnection();
			String sql = "SELECT COUNT(*) AS server_num FROM serverDB";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				pageCnt = rs.getInt("server_num")/WRITING_PER_PAGE + 1;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
		return pageCnt;
	}
					
	//보유현황 페이지 읽어오기
	public ArrayList<String> idcClientAllServerList(){
		ArrayList<String> names=new ArrayList<String>();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		
		try{
			conn = ds.getConnection();
			String sql = "SELECT client_name FROM clientdb ORDER BY client_num desc";
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			while(rs.next())
			{
				names.add(rs.getString("client_name"));
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(conn!=null) conn.close();
				if(pstmt!=null) pstmt.close();
				if(rs!=null) rs.close();
			}catch (SQLException e){
				e.printStackTrace();
			}
		}
		
		return names;
	}
	
	
	
	//게시글 삭제DB에 저장
	public void idcClientDeleteDB(IdcClientDBDTO dto, boolean isClientDB){
		
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null;
		ResultSet rs = null,rs2=null;
		
		String client_delete_date="";
		String client_value="";
		String clientDB="clientdb";
		
		if(isClientDB){
			clientDB="client_deletedb";
			client_delete_date="client_delete_date,";
			client_value="?,";	
		}
		try{
			int index=1;
			conn = ds.getConnection();
			
			String sql="SELECT COUNT(*) as a FROM "+clientDB+" WHERE client_num";
			pstmt2=conn.prepareStatement(sql);
			rs2 = pstmt2.executeQuery();
			int number=0;
			
			if(rs2.next()){
				number = rs2.getInt("a")+1;
			}
				
			sql = "INSERT INTO "+clientDB+" (client_code, client_num, client_name,client_reseller,client_phone1,client_phone2, client_email1,";
			sql+="client_email2,client_receive_date,client_renew_date,"+client_delete_date+"client_note) ";
			sql+="values(?,?,?,?,?,?,?,?,?,"+client_value+"curdate(),?)";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(index++, dto.getClient_code());
			pstmt.setInt(index++, number);
			pstmt.setString(index++, dto.getClient_name());
			pstmt.setString(index++, dto.getClient_reseller());
			pstmt.setString(index++, dto.getClient_phone1());
			pstmt.setString(index++, dto.getClient_phone2());
			pstmt.setString(index++, dto.getClient_email1());
			pstmt.setString(index++, dto.getClient_email2());
			pstmt.setDate(index++, dto.getClient_receive_date());
			if(isClientDB)pstmt.setDate(index++, dto.getClient_renew_date());
			pstmt.setString(index, dto.getClient_note());
			
			pstmt.executeUpdate();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(conn!=null) conn.close();
				if(pstmt!=null) pstmt.close();
				if(pstmt2!=null) pstmt2.close();
				if(rs!=null) rs.close();
				if(rs2!=null) rs2.close();
			}catch (SQLException e){
				e.printStackTrace();
			}
		}
	}
		
		
	//게시글 삭제
	public IdcClientDBDTO idcClientDBDelete(String code, boolean isClientDB)
	{
		String client;
		if(isClientDB){
			client = "clientdb";
		}else{
			client = "client_deletedb";
		}
					
		IdcClientDBDTO dto=new IdcClientDBDTO();
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null, pstmt3=null;
		ResultSet rs = null,rs2=null;
		
		try{
			conn = ds.getConnection();
			
			String sql = "SELECT client_code, client_name, client_reseller, client_phone1, client_phone2, client_email1, ";
			sql+= "client_email2, client_receive_date, client_renew_date, client_note ";
			sql+= "FROM " + client + " WHERE client_code=?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, code);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				dto.setClient_code(rs.getString("client_code"));
				dto.setClient_name(rs.getString("client_name"));
				dto.setClient_reseller(rs.getString("client_reseller"));
				dto.setClient_phone1(rs.getString("client_phone1"));
				dto.setClient_phone2(rs.getString("client_phone2"));
				dto.setClient_email1(rs.getString("client_email1"));
				dto.setClient_email2(rs.getString("client_email2"));
				dto.setClient_receive_date(rs.getDate("client_receive_date"));
				dto.setClient_renew_date(rs.getDate("client_renew_date"));
				dto.setClient_note(rs.getString("client_note"));
			}
			
			sql = "DELETE FROM "+ client + " WHERE client_code = ?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, code);
			pstmt2.executeUpdate();
			
			//havelist에서 리셀러가 존재할 경우 삭제함
			if(dto.getClient_reseller()!="0")
			{
				sql="DELETE FROM havelist WHERE client_code='"+dto.getClient_code()+"' ";
				pstmt3=conn.prepareStatement(sql);
				pstmt3.executeUpdate();
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(conn!=null) conn.close();
				if(pstmt!=null) pstmt.close();
				if(pstmt2!=null) pstmt2.close();
				if(rs!=null) rs.close();
				if(rs2!=null) rs2.close();				
			}catch (SQLException e){
				e.printStackTrace();
			}
		}
		return dto;
	}
	
	//고객 수정시 기존 입력정보 가져오기
	public IdcClientDBDTO idcClientDBModifyForm(int inputNum){
		
		IdcClientDBDTO writing = new IdcClientDBDTO();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try{
			conn = ds.getConnection();
			String sql = "SELECT client_num, client_code, client_name, client_reseller, client_phone1, client_phone2, ";
			sql+="client_email1, client_email2, client_receive_date, client_renew_date, client_note ";
			sql+="FROM clientdb WHERE client_num = ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, inputNum);
			
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				
				String client_code = rs.getString("client_code");
				String client_name = rs.getString("client_name");
				String client_reseller = rs.getString("client_reseller");
				String client_phone1 = rs.getString("client_phone1");
				String client_phone2 = rs.getString("client_phone2");
				String client_email1 = rs.getString("client_email1");
				String client_email2 = rs.getString("client_email2");
				Date client_receive_date = rs.getDate("client_receive_date");
				Date client_renew_date = rs.getDate("client_renew_date");
				String client_note = rs.getString("client_note");
				
				writing.setClient_code(client_code);
				writing.setClient_name(client_name);
				writing.setClient_reseller(client_reseller);
				writing.setClient_phone1(client_phone1);
				writing.setClient_phone2(client_phone2);
				writing.setClient_email1(client_email1);
				writing.setClient_email2(client_email2);
				writing.setClient_receive_date(client_receive_date);
				writing.setClient_renew_date(client_renew_date);
				writing.setClient_note(client_note);				
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(rs!=null) rs.close();
				if(pstmt!=null) pstmt.close();
				if(conn != null) conn.close();
			}catch (SQLException e){
				e.printStackTrace();
			}
		}
		return writing;
	}
	
	//게시글 수정 기능 수행
	public void idcClientDBModify(int inputNumber, String client_name, String client_reseller, String client_phone1,
												String client_phone2, String client_email1, String client_email2, String client_note){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try{
			conn=ds.getConnection();
			String sql = "UPDATE clientdb SET client_name = ?,client_reseller = ?,client_phone1 = ?,";
			sql+="client_phone2 = ?, client_email1 = ?, client_email2 = ?, client_note = ?, client_renew_date = curdate() ";
			sql+="WHERE client_num = ?";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, client_name);
			pstmt.setString(2, client_reseller);
			pstmt.setString(3, client_phone1);
			pstmt.setString(4, client_phone2);
			pstmt.setString(5, client_email1);
			pstmt.setString(6, client_email2);
			pstmt.setString(7, client_note);
			pstmt.setInt(8, inputNumber);
			
			pstmt.executeUpdate();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
	 			if(rs!=null)rs.close();
	 			if(pstmt!=null)pstmt.close();
	 			if(conn!=null)conn.close();
	 		}catch(SQLException e){
	 			e.printStackTrace();
	 		}
		}
	}
	//게시글 등록 기능 수행	
	public void idcClientDBWrite(String code, String name, String reseller, String phone1, String phone2,
												String email1, String email2, String note){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		
		try{
			conn=ds.getConnection();
			String sql = "INSERT INTO clientdb(client_code, client_name,client_reseller,client_phone1,client_phone2, client_email1,";
			sql+="client_email2,client_receive_date,client_renew_date,client_note) ";
			sql+="values(?,?,?,?,?,?,?,curdate(),curdate(),?)";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, code);
			pstmt.setString(2, name);
			pstmt.setString(3, reseller);
			pstmt.setString(4, phone1);
			pstmt.setString(5, phone2);
			pstmt.setString(6, email1);
			pstmt.setString(7, email2);
			pstmt.setString(8, note);
			
			pstmt.executeUpdate();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
	 			if(rs!=null)rs.close();
	 			if(pstmt!=null)pstmt.close();
	 			if(conn!=null)conn.close();
	 		}
	 		catch(SQLException e)
	 		{
	 			e.printStackTrace();
	 		}
		}
	}
	
	 public ArrayList<IdcClientDBDTO> idcClientDBList(String curPage, boolean isClientDB){
		 
		ArrayList<IdcClientDBDTO> list = new ArrayList<IdcClientDBDTO>();
	 	Connection conn = null;
	 	PreparedStatement pstmt = null, pstmt2 = null, pstmt3 = null;
	 	ResultSet rs = null, rs2 = null, rs3 = null;
	 	
	 	int numbering_end =WRITING_PER_PAGE*(Integer.parseInt(curPage)-1) ;
	 	int numbering=0;
	 	
	 	try{
	 		conn = ds.getConnection();	 		
	 		String sql = "SELECT COUNT(*) as a FROM clientdb";
	 		pstmt2 = conn.prepareStatement(sql);
	 		rs2 = pstmt2.executeQuery();
	 		if(rs2.next()){
	 			numbering = rs2.getInt("a")-numbering_end;
	 		}

	 		sql = "SELECT Client_Num, client_code, client_name, client_reseller, client_phone1, client_phone2,";
	 				sql+="client_email1, client_email2, client_receive_date, client_renew_date, ";
	 		if(isClientDB){
	 			sql+="client_note FROM clientdb ORDER BY client_num desc ";
 		 		pstmt = conn.prepareStatement(sql);
	 		}else{
	 			sql+="client_delete_date, client_note FROM client_deletedb ORDER BY client_num desc ";;
 				sql+="LIMIT ?,? ";
 				
 		 		pstmt = conn.prepareStatement(sql);
 		 		pstmt.setInt(1,numbering_end);
 		 		pstmt.setInt(2,WRITING_PER_PAGE);
	 		}
	 		rs = pstmt.executeQuery();
	 		System.out.println("IdcDAO에서 참고:"+pstmt); 				
	 		
	 		while(rs.next()){
	 			int client_num = numbering--;
	 			String client_code = rs.getString("client_code");
	 			String client_name = rs.getString("client_name");
	 			String client_reseller = rs.getString("client_reseller");
	 			String client_phone1 = rs.getString("client_phone1");
	 			String client_phone2 = rs.getString("client_phone2");
	 			String client_email1 = rs.getString("client_email1");
	 			String client_email2 = rs.getString("client_email2");
	 			Date client_receive_date = rs.getDate("client_receive_date");
	 			Date client_renew_date = rs.getDate("client_renew_date");
	 			Date client_delete_date = null;
	 			
	 			if(!isClientDB)
	 				 client_delete_date= rs.getDate("client_delete_date");
	 			String client_note = rs.getString("client_note");
	 			
	 			IdcClientDBDTO writing = new IdcClientDBDTO();
	 			
	 			writing.setClient_num(client_num);
	 			writing.setClient_code(client_code);
	 			writing.setClient_name(client_name);
	 			writing.setClient_reseller(client_reseller);
	 			writing.setClient_phone1(client_phone1);
	 			writing.setClient_phone2(client_phone2);
	 			writing.setClient_email1(client_email1);
	 			writing.setClient_email2(client_email2);
	 			writing.setClient_receive_date(client_receive_date);
	 			writing.setClient_renew_date(client_renew_date);
	 			if(!isClientDB)	 				
	 				writing.setClient_delete_date(client_delete_date);
	 			writing.setClient_note(client_note);
	 			
	 			
	 			sql = "SELECT count(*) as num FROM serviceDB WHERE client_code=?";
				pstmt3 = conn.prepareStatement(sql);
				pstmt3.setString(1, client_code);
				rs3 = pstmt3.executeQuery();
				
				String client_check = "";
				int num = 0;
				
				if(rs3.next()){
					num = rs3.getInt("num");
				}
				
				if(num == 0){
					client_check = "y";
				}else{
					client_check = "n";
				}				
				writing.setClient_check(client_check);		 			
	 			
	 			list.add(writing);
	 		}
	 	}catch(Exception e){
	 		e.printStackTrace();
	 	}finally{
	 		try{
	 			if(rs!=null)rs.close();
	 			if(pstmt!=null)pstmt.close();
	 			if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(rs3 != null) rs3.close();
				if(pstmt3 != null) pstmt3.close();
	 			if(conn!=null)conn.close();
	 		}catch(SQLException e){
	 			e.printStackTrace();
	 		}
	 	}
	 	return list;
	 }
	 
	 //게시판의 페이징 처리를 위한 코드
	 public int idcClientDBPageCnt(boolean isClientDB){
		 int pageCnt = 0;
		 
		 Connection conn = null;
		 PreparedStatement pstmt = null;
		 ResultSet rs = null;
		 
		 try{
			 conn=ds.getConnection();
			 String sql = "SELECT COUNT(*) AS client_num FROM ";
			 if(isClientDB){
				 sql+="clientdb";
			 }else{
				 sql+="client_deletedb";
			 }
				 			 
			 pstmt = conn.prepareStatement(sql);
			 rs = pstmt.executeQuery();
			 if(rs.next()){
				 pageCnt = rs.getInt("client_num") / WRITING_PER_PAGE+1;
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 try{
		 			if(rs!=null)rs.close();
		 			if(pstmt!=null)pstmt.close();
		 			if(conn!=null)conn.close();
		 		}catch(SQLException e){
		 			e.printStackTrace();
		 		}
		 }
		 return pageCnt;
	 }
}