package idc.main.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcGearDBDTO2;

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

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

public class IdcNewServerInsertCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcNewServerInsertCmd()
	{
		dao = new IdcDAO();
	}
	
	//새로운 재원장비 등록
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request))
		{
			request.setAttribute("reError", dao.reError);
			return;
		}
		else
		{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
		
		String[] spec = request.getParameterValues("spec");
		String[] cpuName = request.getParameterValues("cpuName");
		String selValue = request.getParameter("selValue");
		String[] selValue2 = request.getParameterValues("selValue2");
		String[] price = request.getParameterValues("price");
		int firarr = Integer.parseInt(request.getParameter("firarr"));
		ArraySort(spec, cpuName, selValue2);
		if(setNewCore(spec, cpuName, selValue2, selValue, price, firarr))
			idcNewServerInsertCmd(selValue, spec, cpuName,selValue2, price);
	}
	
	//완전 새로운 기종일경우
	private boolean setNewCore(String[] spec, String[] cpuname, String[] selValue2, String selValue, String[] price, int firarr)
	{
		boolean result = false;
		
		Connection conn=null;
		PreparedStatement pstmt=null,pstmt2=null;
		ResultSet rs=null;
		LinkedList<IdcGearDBDTO2> list = new LinkedList<IdcGearDBDTO2>();
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM gearlist WHERE firarr=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, firarr);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				result = true;
			}
			if(!result)
			{
				setList(cpuname, spec, selValue2, selValue, price, firarr, list);
				sql="INSERT INTO gearlist (firarr, secarr, process, cpuname, spec, price) values(?,?,?,?,?,?)";
				pstmt2 = conn.prepareStatement(sql);
				for(int i=0;i<list.size();i++)
				{
					IdcGearDBDTO2 dto = list.get(i);
					pstmt2.setInt(1, dto.getFirarr());
					pstmt2.setInt(2, dto.getSecarr());
					pstmt2.setString(3, dto.getProcess());
					pstmt2.setString(4, dto.getCpuname());
					pstmt2.setString(5, dto.getSpec());
					pstmt2.setInt(6, dto.getPrice());
					pstmt2.executeUpdate();
				}
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcNewServerInsertCmd - setNewCore 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcNewServerInsertCmd - setNewCore 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	//새로 등록시 정렬해주기.
	private void ArraySort( String[] spec, String[] cpuName, String[] selValue2)
	{
		String specTemp,selValue2Temp,cpuNameTemp;
		int[] a = new int[selValue2.length];
		
		for(int i=0;i<selValue2.length;i++)
			a[i] = Integer.parseInt(selValue2[i]);
		
		for(int i=0;i<spec.length-1;i++)
		{
			for(int j=i+1;j<spec.length;j++)
			{
				if(a[i] > a[j])
				{
					selValue2Temp = selValue2[i];
					specTemp = spec[i];
					cpuNameTemp = cpuName[i];
					
					selValue2[i] = selValue2[j];
					spec[i] = spec[j];
					cpuName[i] = cpuName[j];
					
					selValue2[j] = selValue2Temp;
					spec[j] = specTemp;
					cpuName[j] = cpuNameTemp;
				}
			}
		}
	}
	
	//데이터 삽입.
	private void idcNewServerInsertCmd(String selValue, String[] spec, String[] cpuName, String[] selValue2, String[] price)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null,pstmt3=null;
		ResultSet rs=null;
		LinkedList<IdcGearDBDTO2> list = new LinkedList<IdcGearDBDTO2>();
		ArrayList<IdcGearDBDTO2> tlist = new ArrayList<IdcGearDBDTO2>();
		
		int firarr=0;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM gearList ";
			sql+= "WHERE process = ? ";
			sql+= "ORDER BY firarr ASC, secarr ASC ";
			
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, selValue);
			rs = pstmt2.executeQuery();
			
			while(rs.next())
			{
				IdcGearDBDTO2 dto = new IdcGearDBDTO2();
				dto.setFirarr(firarr = rs.getInt("firarr"));
				dto.setCpuname(rs.getString("cpuname"));
				dto.setProcess(rs.getString("process"));
				dto.setSpec(rs.getString("spec"));
				dto.setPrice(rs.getInt("price"));
				
				list.add(dto);
				tlist.add(dto);
			}
			setList(cpuName, spec, selValue2, selValue, price, firarr, list);
		
			sql="UPDATE gearlist SET firarr = ?,secarr = ?,process = ?,spec = ?,cpuname = ?, price = ? ";
			sql+="WHERE cpuname = ?";
			pstmt =conn.prepareStatement(sql);
			
			sql="INSERT INTO gearlist (firarr,secarr,process,spec,cpuname,price) values(?,?,?,?,?,?) ";
			pstmt3 =conn.prepareStatement(sql);

			//기존에 존재한 데이터인지 아닌지 체크하여 존재하면 수정 없으면 입력으로 가른다.
			boolean check=true;
			for(int i=0;i<list.size();i++)
			{
				check=true;
				IdcGearDBDTO2 dto = list.get(i);
				for(int j=0;j<tlist.size();j++)
				{
					if(dto.getSpec()==tlist.get(j).getSpec())
					{
						check=false;
						break;
					}
				}
				if(check)
				{
					pstmt3.setInt(1, firarr);
					pstmt3.setInt(2, dto.getSecarr());
					pstmt3.setString(3, dto.getProcess());
					pstmt3.setString(4, dto.getSpec());
					pstmt3.setString(5, dto.getCpuname());
					pstmt3.setInt(6, dto.getPrice());
					pstmt3.executeUpdate();
				}
				else
				{
					pstmt.setInt(1, firarr);
					pstmt.setInt(2, dto.getSecarr());
					pstmt.setString(3, dto.getProcess());
					pstmt.setString(4, dto.getSpec());
					pstmt.setString(5, dto.getCpuname());
					pstmt.setInt(6, dto.getPrice());
					pstmt.setString(7, dto.getCpuname());
					pstmt.executeUpdate();
				}
			}
			//list 2번째값 재등록 차례대로.
			for(int i=0;i<list.size();i++)
				list.get(i).setSecarr(i);
		}
		catch (Exception e) 
		{
			System.out.println("IdcNewServerInsertCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				if(pstmt3!=null)pstmt3.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcNewServerInsertCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private void setList(String[] cpuname, String[] spec, String[] selValue2, String selValue, String[] price, int firarr, LinkedList<IdcGearDBDTO2> list)
	{
		for(int i=0;i<selValue2.length;i++)
		{
			IdcGearDBDTO2 dto = new IdcGearDBDTO2();
			dto.setCpuname(cpuname[i]);
			dto.setProcess(selValue);
			dto.setSpec(spec[i]);
			dto.setPrice(Integer.parseInt(price[i]));
			dto.setFirarr(firarr);
			
			int a=Integer.parseInt(selValue2[i])-1;
			if(list.size()<=a)
				a=list.size();
			else if(a<0)
				a=0;
			list.add(a,dto);
		}
		
		for(int i=0;i<list.size();i++)
			list.get(i).setSecarr(i);
//		for(int i=0;i<list.size();i++)
//			System.out.println(list.get(i).getSpec());
	}
}
