package kr.co.swh.lecture.opensource.jsoup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.collect.Lists;

/**
 * <pre>
 * kr.co.swh.lecture.opensource.jsoup 
 * Naver.java
 *
 * 설명 :
 * </pre>
 * 
 * @since : 2018. 9. 2.
 * @author : tobby48
 * @version : v1.0
 */
public class Naver {
	
	private Document doc;
	private final String MovieURL = "https://movie.naver.com/movie";
	
	public Naver() throws IOException{
		doc = Jsoup.connect(MovieURL + "/sdb/rank/rmovie.nhn").get();
		System.out.println(doc.title());
	}
	
	
	public void movieRanking() {
		List<NaverMovieInfo> movieList = new ArrayList<NaverMovieInfo>();
		int ranking = 1;
		
		Elements fetchTmpDatas = doc.select("div[class=tit3]");
		for(Element e : fetchTmpDatas){
			NaverMovieInfo movie = new NaverMovieInfo();
			movie.setTitle(e.text());
			movie.setRanking(ranking);
			
			Element aTag = e.selectFirst("a");
			movie.setUrl(aTag.attr("href"));
			try {
				movie.setRepleList(movieReple(movie.getUrl()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			ranking++;
			movieList.add(movie);
		}
		
		for(NaverMovieInfo movie : movieList){
			System.out.println(movie);
		}
	}
	
	private List<NaverMovieReple> movieReple(String url) throws IOException{
		List<NaverMovieReple> repleList = Lists.newArrayList();
		Document repleDoc = Jsoup.connect(MovieURL + url).get();
		Elements repleDatas = repleDoc.select("div[class=score_reple]");
		Elements repleSympathy = repleDoc.select("div[class=btn_area]").select("span");
		int repleIndex = 0;
		
		for(Element e : repleDatas){
			NaverMovieReple reple = new NaverMovieReple();
			reple.setText(e.select("p").text());
			reple.setSympathy(Integer.parseInt(repleSympathy.get(repleIndex+1).text()));
			reple.setNotSympathy(Integer.parseInt(repleSympathy.get(repleIndex+3).text()));
			repleList.add(reple);
			repleIndex+=4;
		}
		
		return repleList;
	}

}
