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.List;
import java.util.Map;

import org.bitbucket.eunjeon.seunjeon.Analyzer;
import org.bitbucket.eunjeon.seunjeon.LNode;
import org.bitbucket.eunjeon.seunjeon.Morpheme;

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


public class Step2 {
	
	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;

	List<WordCloud> result =  new ArrayList<WordCloud>();
	
	public Step2() throws ClassNotFoundException, SQLException {
		Class.forName(JDBC_DRIVER);
		conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
	}
	
	public void excute() {
		port(45678);
		Map<String, Object> attributes = new HashMap<>();
		
		get("/news/cloud", (request, response) -> {
			Map<String, Integer> contents = new HashMap<String, Integer>();
				
			String acQuery = "select script from NEWS limit 10";
			stmt = conn.createStatement();
			res = stmt.executeQuery(acQuery);
			while (res.next()) {
				for (LNode node : Analyzer.parseJava(res.getString("script"))) {
					Morpheme m = node.morpheme();
//					System.out.println(m.surface() + " / 품사:" + m.feature().head());
					if(m.feature().head().equalsIgnoreCase("nnp") || m.feature().head().equalsIgnoreCase("nng")) {
						WordCloud w = null;
						if(contents.containsKey(m.surface())) {
							contents.put(m.surface(), contents.get(m.surface()) + 1);
							w = new WordCloud(m.surface(), contents.get(m.surface()) + 1);
						}else {
							contents.put(m.surface(), 1);
							w = new WordCloud(m.surface(), 1);
						}
						result.remove(w);
						result.add(w);
					}
				}
			}

			attributes.put("message", result);
			return modelAndView(attributes, "news-cloud.ftl");
		}, new FreeMarkerTemplateEngine());
	}
	public static void main(String[] args) {
		
		Step2 s;
		try {
			s = new Step2();
			s.excute();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}