package idc.server.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utility.StringToDate;
import 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;

public class IdcServerListCmd implements IdcCmd{
	
	private int WRITING_PER_PAGE = 100;
	IdcDAO dao = new IdcDAO(); 
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		ArrayList<IdcServerDTO> list; 
		
		String sc = "", so = "", sn = "";
		sc=request.getParameter("searchContent");
		if(!(sc!=null && sc!=""))
			sc="";
		so=request.getParameter("searchOption");						
		if(!(so!=null && so!=""))
			so="mkall";
		
		//포맷보류 필터링(전체(all)/포맷보류(format)/일반(nomal));
		String format_filter = request.getParameter("format_filter");
		if(format_filter == null || format_filter == ""){
			format_filter = "";
		}
		
		//포맷보류 날짜 선택시
		String str_date = request.getParameter("select_date");
		StringToDate st = new StringToDate();
		Date select_date; 						
		if(str_date == "" || str_date == null){
			select_date = null;
		}else{
			select_date = st.stringToDate(str_date);
		}
								
		int pageCnt = getPageCnt(sc,so, format_filter, select_date);
		int curPage = getCurPage(request.getParameter("curPage"));
		int firstPage = getFirstPage(pageCnt,curPage);
		int endPage = getEndPage(firstPage, pageCnt);
		list = idcServerList(Integer.toString(curPage), sc, so, format_filter, select_date);
		
		request.setAttribute("idcServerList", list);
		request.setAttribute("pageCnt", pageCnt);
		request.setAttribute("curPage", curPage);
		request.setAttribute("firstPage", firstPage);
		request.setAttribute("endPage", endPage);
		request.setAttribute("searchOption",so);
		request.setAttribute("searchContent", sc);
		request.setAttribute("format_filter", format_filter);
		request.setAttribute("select_date", select_date);
		
		switch(so)
		{
		    case "mkall":sn="전체검색";break;
			case "server_use_status":sn="가용";break;
			case "server_code":sn="장비명";break;
			case "server_cpuname":sn="cpu";break;
		}
		request.setAttribute("searchOptionName",sn);
	}
	
	//현재 페이지
	private int getCurPage(String strPage){
		int curPage=1;
		
		if(strPage !=null && strPage!="")
			curPage=Integer.parseInt(strPage);
		
		return curPage;
	}
	
	//페이지 카운트 
	private int getPageCnt(String sc, String so, String filter, Date select_date){
		int pageCnt=1;
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try{
			conn=dao.getConn();
			//String sql="SELECT COUNT(*) as a FROM serverdb WHERE "+so+" like '%"+sc+"%' ";
			//SELECT COUNT(*) as a FROM serverdb where server_code like '%DQ%' OR (server_use_status like '%DQ%' or server_cpuname like '%DQ%')
			String sql="SELECT COUNT(*) as a FROM serverdb WHERE  server_code like '%"+sc+"%' OR (server_note like '%"+sc+"%' or server_use_status like '%"+sc+"%' or server_cpuname like '%"+sc+"%') ";
			if(filter.equals("format")){
				sql += " and server_fomat_date is not null and server_use_status ='n'";
			}else if(filter.equals("normal")){
				sql += " and server_use_status ='y'";
			}
			
			if(select_date != null){
				sql += " and server_fomat_date=? ";
				pstmt =conn.prepareStatement(sql);
				pstmt.setDate(1, select_date);
			}else{
				pstmt =conn.prepareStatement(sql);
			}
						
			rs = pstmt.executeQuery();
			if(rs.next()){
				int num = rs.getInt("a");				
				if(num%WRITING_PER_PAGE == 0){
					pageCnt = num/WRITING_PER_PAGE;
				}else{
					pageCnt = num/WRITING_PER_PAGE + 1;
				}
			}
				//pageCnt = rs.getInt("a")/dao.WRITING_PER_PAGE+1;
		}
		catch (Exception e) 
		{
			System.out.println("IdcServerListCmd - pageCnt 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcServerListCmd - pageCnt  에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return pageCnt;
	}
	
	//첫페이지
	private int getFirstPage(int pageCnt, int curPage)
	{
		int firstPage = 1;
		if(pageCnt-10>1)
			firstPage=pageCnt-10;
		
		int div =0;
		if(firstPage>=curPage)
			div = firstPage-curPage;
		firstPage-=div;
		
		return firstPage;
	}
	
	//마지막 페이지
	private int getEndPage(int firstPage, int pageCnt)
	{
		int endPage = pageCnt;
		
		int div = pageCnt-firstPage;
		if(div>10)
			endPage-=div-10;
		return endPage;
	}
	
	//서버 리스트 록록 조회 기능 수행
	public ArrayList<IdcServerDTO> idcServerList(String curPage, String sc, String so, String filter, Date select_date){
		
		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 = dao.getConn();
	//		String sql = "SELECT COUNT(*) as a FROM serverdb WHERE "+so+" like '%"+sc+"%' ";
			String sql = "SELECT COUNT(*) as a FROM serverdb WHERE  server_code like '%"+sc+"%' OR (server_note like '%"+sc+"%' or server_use_status like '%"+sc+"%' or server_cpuname like '%"+sc+"%')  ";
			if(filter.equals("format")){
				sql += " and server_fomat_date is not null and server_use_status ='n' ";
			}else if(filter.equals("normal")){
				sql += " and server_use_status ='y' ";
			}

			if(select_date != null){
				sql += " and server_fomat_date=? ";
				pstmt2 =conn.prepareStatement(sql);
				pstmt2.setDate(1, select_date);
			}else{
				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_process, server_spec, server_cpuname, 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 ";
			//sql += "WHERE "+so+" like '%"+sc+"%' ";
			sql += " WHERE  server_code like '%"+sc+"%' OR (server_note like '%"+sc+"%' or server_use_status like '%"+sc+"%' or server_cpuname like '%"+sc+"%')";
			if(filter.equals("format")){
				sql += " and server_fomat_date is not null and server_use_status ='n'";
			}else if(filter.equals("normal")){
				sql += " and server_use_status ='y'";
			}
			
			if(select_date != null){
				sql += " and server_fomat_date=? ";				
				sql += " ORDER BY server_num desc LIMIT ?, ?";			
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, select_date);
				pstmt.setInt(2, numbering_end);
				pstmt.setInt(3, WRITING_PER_PAGE);
				
			}else{
				sql += " ORDER BY server_num desc LIMIT ?, ?";			
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, numbering_end);
				pstmt.setInt(2, WRITING_PER_PAGE);
			}
												
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				int num = numbering--;
				int server_num = rs.getInt("server_num");
				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.setNumber(num);
				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;
		
	}

}
