package kr.co.swh.lecture.opensource.project.sparkjava;


import static spark.Spark.get;
import static spark.Spark.modelAndView;
import static spark.Spark.port;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import kr.co.swh.lecture.opensource.sparkjava.FreeMarkerTemplateEngine;


public class Step1 {
	
	final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	final String DB_URL = "jdbc:mysql://dev-swh.ga:3306/market";
	
	final String USERNAME = "root";
	final String PASSWORD = "swhacademy!";
	
	Statement stmt;
	ResultSet res;
	Connection conn = null;

	public Step1() throws ClassNotFoundException, SQLException {
		Class.forName(JDBC_DRIVER);
		conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
	}
	
	public void excute() {
		port(45678);
		ArrayList<Object> jArr = new ArrayList<Object>();
		Map<String, Object> attributes = new HashMap<>();
		
		get("/news/:0or1/:column/:row", (request, response) -> {
			String acc = request.params("0or1");
			String column = request.params("column");
			String row = request.params("row");
			
			if(conn.isClosed()) conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
			stmt = conn.createStatement();
			
			String acQuery = "select * from NEWS where " + column + " = " + "'" +  row + "'";
			String inacQuery = "select * from NEWS where " + column + " like " + "'%" +  row + "%'";
			if(acc.equals("1")) res = stmt.executeQuery(acQuery);
			else res = stmt.executeQuery(inacQuery);
			while (res.next()) {
				News i = new News(res.getString("category"), res.getString("id"), res.getString("date"), res.getString("title"), res.getString("script"));
				String academy2Json = new Gson().toJson(i);		
				jArr.add(i);		// json문자열로 넣지 말고, 객체형태로 추가
			}
			attributes.put("message", jArr);
			return modelAndView(attributes, "news-table.ftl");
		}, new FreeMarkerTemplateEngine());
	}
	public static void main(String[] args) {
		
		Step1 s;
		try {
			s = new Step1();
			s.excute();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}