/**
 * 
 */
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.Account;
import org.mynonglam.entitys.FriendList;

/**
 * @author Dao
 *
 */
public class FriendListDAO {
	private static Connection connection;
	private static PreparedStatement statement = null;
	private ResultSet resultSet;
	/**
	 * 
	 */
	public FriendListDAO() {
		connection = ConnectionDTB.getConnection();
	}
	
	public ArrayList<FriendList> getFriends(String idacc) {
		ArrayList<FriendList> result = new ArrayList<FriendList>();
		
		String sql = "SELECT emailfrom, emailto FROM relationship where (emailfrom=? or emailto=?) AND isaccept = 1";
		try {
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setString(1, idacc);
			statement.setString(2, idacc);
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				String emailfrom = resultSet.getString("emailfrom");
				String emailto = resultSet.getString("emailto");
				System.out.println(emailfrom + "  " + emailto);
				String idusername = "";
				if(emailfrom.equals(idacc)) {
					idusername = emailto;
				} else if(emailto.equals(idacc)) {
					idusername = emailfrom;
				}
				Account account = new AccountDAO().getAccountInfoByComment(idusername);
				if(account != null) {
					result.add(new FriendList(account.getEmail(), account.getFullname(), account.getAvatar()));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public ArrayList<FriendList> getFriendsLimit(String idacc, int offest, int lenght) {
		ArrayList<FriendList> result = new ArrayList<FriendList>();
		
		String sql = "SELECT emailfrom, emailto FROM relationship where (emailfrom=? or emailto=?) AND isaccept = 1 LIMIT ?,?";
		try {
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setString(1, idacc);
			statement.setString(2, idacc);
			statement.setInt(3, offest);
			statement.setInt(4, lenght);
			
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				String emailfrom = resultSet.getString("emailfrom");
				String emailto = resultSet.getString("emailto");
				System.out.println(emailfrom + "  " + emailto);
				String idusername = "";
				if(emailfrom.equals(idacc)) {
					idusername = emailto;
				} else if(emailto.equals(idacc)) {
					idusername = emailfrom;
				}
				Account account = new AccountDAO().getAccountInfoByComment(idusername);
				if(account != null) {
					result.add(new FriendList(account.getEmail(), account.getFullname(), account.getAvatar()));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
//	public static void main(String[] args) {
//		System.out.println(new FriendListDAO().getFriends("dlduynam@gmail.com").get(0).getRealname());
//	}

}
