/**
 * 
 */
package org.mynonglam.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.mynonglam.connectdb.ConnectionDTB;
import org.mynonglam.entitys.NewInfo;
import org.mynonglam.entitys.Status;

/**
 * @author Dao
 *
 */
public class NewsDAO {
	
	private static Connection connection;
	private static PreparedStatement statement = null;
	private ResultSet resultSet;
	
	private StatusDAO statusDAO;
	private AccountDAO accountDAO;
	
	/**
	 * 
	 */
	public NewsDAO() {
		connection = ConnectionDTB.getConnection();
		statusDAO = new StatusDAO();
		accountDAO = new AccountDAO();
	}
	
	public ArrayList<NewInfo> getNewsLimit(String idacc, int start, int lenght) {
		ArrayList<NewInfo> result = new ArrayList<NewInfo>();
		
		String sql = "SELECT id, email, datecreate, idtable, nametable FROM newinfo where email=? ORDER BY id DESC LIMIT ?,?";
		
		try {
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setString(1, idacc);
			statement.setInt(2, start);
			statement.setInt(3, lenght);
			
			ResultSet resultSet = statement.executeQuery();
			while(resultSet.next()) {
				NewInfo temp = new NewInfo();
				temp.setId(resultSet.getString("id"));
				temp.setEmail(idacc);
				temp.setDatecreate(resultSet.getString("datecreate"));
				temp.setIdtable(resultSet.getString("idtable"));
				temp.setNametable(resultSet.getString("nametable"));
				
				result.add(temp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public Status getStatusForNews(String id) {
		Status result = null;
		
		String sql = "SELECT idstatus, email, idshare, content, datecreate FROM status WHERE idstatus=?";
		try {
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setString(1, id);
			ResultSet resultSet = statement.executeQuery();
			
			if(resultSet.next()) {
				result = new Status();
				result.setIdstatus(id);
				result.setContent(resultSet.getString("content"));
				result.setDatecreate(resultSet.getString("datecreate"));
				result.setCommentstatuses(statusDAO.getCommentStatus(id));
				result.setAccount(accountDAO.getAccountInfoByComment(resultSet.getString("email")));
				result.setStatuslikes(statusDAO.getStatusLike(id));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static void main(String[] args) {
//		long time = 1l;
//		Calendar ca = Calendar.getInstance();
//		ca.setTimeInMillis(time);
//		System.out.println(ca.get);
		System.out.println(new NewsDAO().getStatusForNews("ST000000000000000001").toString());
	}

}
