/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.siso.horario.MySqlDAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.JSONObject;
import pe.siso.horario.DAO.PlanAcademicoDAO;

/**
 *
 * @author sistem20user
 */
public class MySqlPlanAcademicoDAO implements PlanAcademicoDAO{

	@Override
	public int insertarPlanAcademico(JSONObject json) throws Exception {
		
		int resultado = 0;
		int dato = 0;
		Connection cnx = null;

		try {

		  cnx = MySqlDAOFactory.obtenerConexion("horario");
			Statement st = cnx.createStatement();
			System.out.println("json--->"+json);
			 String sql = "SELECT COUNT(*) as contador FROM detalle_plan_academico WHERE cadena_plana != '' and cod_area="+json.getInt("codArea")+" and cod_gru_aula = "+json.getInt("codigoGrupoAulas")+"";
			
			System.out.println(sql);
			ResultSet rs = st.executeQuery(sql);
		   String queryDML="";
			if (rs.next()) {
				
			  if (rs.getInt("contador") == 0) {
					
				  queryDML = "INSERT INTO detalle_plan_academico (cod_gru_aula,codperiodo,cadena_plana,cod_area,fecha_registro) VALUES ("+json.getString("codigoGrupoAulas")+","+json.getInt("periodo")+",'"+json.getString("cadenaPlana")+"',"+json.getInt("codArea")+",CURDATE())";
					resultado=1;
			  } else {
					queryDML="UPDATE detalle_plan_academico SET cadena_plana = '"+json.getString("cadenaPlana")+"'  where cod_gru_aula = "+json.getInt("codigoGrupoAulas")+" and cod_area="+json.getInt("codArea")+"";
			    resultado=2;
		  	}
				
				dato = st.executeUpdate(queryDML);
				if(dato == 1){
					resultado = resultado;
				}else{
				  resultado=3;
				}
			}

	

		} catch (SQLException ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (cnx != null) {
					cnx.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("Error al liberar memoria");
			}
		}
		return resultado;
		
		
	}
	
}
