package simulator.interfaces.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import models.algebra.Constant;
import models.algebra.Expression;
import models.algebra.Term;
import models.dataConstraintModel.JsonTerm;
import models.dataConstraintModel.ResourcePath;
import models.dataFlowModel.DataTransferChannel;
import simulator.Resource;
import simulator.Simulator;
import simulator.interfaces.NativeSender;

public class RecordSender extends NativeSender{
	
	private String url;
	private String user;
	private String pass;

	public RecordSender(Simulator simulator, DataTransferChannel channel, ResourcePath resourcePath,
			Resource resource, String url, String user, String pass) {
		super(simulator, channel, resourcePath, resource);
		this.url = url;
		this.user = user;
		this.pass = pass;
	}
	
	public void updateRecord(String tableName, String key, String value) {
		String query = "SELECT * FROM "+ tableName + " WHERE "+ key + " = ?";
		try{
			Connection conn = DriverManager.getConnection(url, user, pass);
			PreparedStatement pstmt = conn.prepareStatement(query);
			pstmt.setString(1, value);
			ResultSet rs = pstmt.executeQuery();
		} catch (SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}
	
	public void updateRecord(String tableName, String key, int value) {
		String query = "SELECT * FROM "+ tableName + " WHERE "+ key + " = ?";
		JsonTerm res = new JsonTerm();
		
		try{
			Connection conn = DriverManager.getConnection(url, user, pass);
			PreparedStatement pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, value);
			ResultSet rs = pstmt.executeQuery();
			
			var meta = rs.getMetaData();
			int primaryNum = -1;
			for(int i = 1; i <= meta.getColumnCount(); i++) {
				if(meta.getColumnName(i).equals(key)) {
					primaryNum = i;
					break;
				}
			}
			
			while(rs.next()) {
				String primaryData = rs.getString(primaryNum);
				res.addMember(primaryData, new JsonTerm());
				for(int i = 1; i <= meta.getColumnCount(); i++) {
					if(i == primaryNum) {
						continue;
					}
					String columnName = meta.getColumnName(i);
					Constant data = new Constant(rs.getString(i));
					((JsonTerm) res.get(primaryData)).addMember(columnName, data);
				}
			}
		} catch (SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
		
		
		Expression message = channel.getOutputChannelMembers().iterator().next().getStateTransition().getMessageExpression();
		message = (Term)message.clone();
		((Term) message).setChild(0, res);
		System.out.println(res);
		sendToModel(message);
		
	}

}
