/**
 * 
 */
package org.mynonglam.controllers;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mynonglam.dao.AccountDAO;
import org.mynonglam.dao.CommentStatusDAO;
import org.mynonglam.dao.Emoticon;
import org.mynonglam.dao.NewsDAO;
import org.mynonglam.dao.NewsInfoDAO;
import org.mynonglam.dao.StatusDAO;
import org.mynonglam.entitys.Account;
import org.mynonglam.entitys.CommentStatus;
import org.mynonglam.entitys.NewInfo;
import org.mynonglam.entitys.Status;
import org.mynonglam.entitys.StatusLike;
import org.mynonglam.server.Notificate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

/**
 * @author Dao
 *
 */
@Controller
public class AccountStatusControl {
	
	private StatusDAO statusDAO;
	private NewsDAO newsDAO;
	private AccountDAO accountDAO;
	private CommentStatusDAO commentStatusDAO;
	private NewsInfoDAO newsInfoDAO;

	/**
	 * 
	 */
	public AccountStatusControl() {
		statusDAO = new StatusDAO();
		newsDAO = new NewsDAO();
		accountDAO = new AccountDAO();
		commentStatusDAO = new CommentStatusDAO();
		newsInfoDAO = new NewsInfoDAO();
	}
	
	@RequestMapping(value = "getnewsacc", method = RequestMethod.POST)
	public @ResponseBody String getNewsInfo(HttpServletRequest request, HttpSession session) {
		String result = "null";
		ArrayList<String> resultnews = new ArrayList<String>();
		String email = (String) session.getAttribute("accountinfo");
		if (email != null) {
			Account acclogin = accountDAO.getAccountInfoByComment(email);
			if(acclogin != null) {
				String idacc = request.getParameter("idacc");
				if(idacc != null) {
					int page = Integer.valueOf(request.getParameter("pagere"));
					int lenght = 1;
					ArrayList<NewInfo> listnew = newsDAO.getNewsLimit(idacc, (page - 1) * lenght, lenght);
					if(listnew.size() > 0) {
						for(NewInfo newinfo : listnew) {
							String idtable = newinfo.getIdtable();
							String tablename = newinfo.getNametable();
							String contentre = "";
							if(tablename.equalsIgnoreCase("status")) {
								Status status = newsDAO.getStatusForNews(idtable);
								if(status != null) { 
									String likmember = "";
									contentre = "<div class='post-view-info poststatus-comment-id-" + status.getIdstatus() + "' idcommentpost='" + status.getIdstatus() + "' type='status'>" +
												"	<div class='post-view-left'>" +
												"		<div class='post-view-avatar' style='background: url(" + status.getAccount().getAvatar() +"); background-size: 100% auto;'></div>" +
												"	</div>" +
												"	<div class='ii'>" +
												"		<div class='load-image ie'> &nbsp; </div>" +
												"		<div class='post-view-right'>";
									if(email.equalsIgnoreCase(status.getAccount().getEmail())) {
										contentre += "		<div class='comment-deleted-status' iddelestatus='" + status.getIdstatus() + "' title='Xóa'>X</div>";
									}
									contentre += "			<div class='post-view-header'>" +
												"				<div style='display: inline;'>" +
												"					<h3 class='ck'><a href='index.jsp?acc=" + status.getAccount().getEmail() + "'>" + status.getAccount().getFullname() + "</a></h3>" +
												"					<span>" + status.getDatecreate() + "</span>" +
												"				</div>" +
												"			</div>" +
												"			<div class='post-view-content'>" + status.getContent() + "</div>" +
												"			<div class='comment'>" +
												"				<div class='content'>";
									boolean checkyoulike = false;
									for(StatusLike sl : status.getStatuslikes()) {
										if(sl.getAccount().getEmail().equalsIgnoreCase(email)) {
											likmember = "<span class='ban-post-like-status'> Bạn</span>" + likmember;
											checkyoulike = true;
										} else {
											likmember += "&nbsp;<a href='index.jsp?acc=" + sl.getAccount().getEmail() + "'><span>" + sl.getAccount().getFullname() + "</span></a>,"; // danh sach thich
										}
									}
									if(checkyoulike) {
										contentre += "				<div class='likecomment'><a href='#' class='status-post-likess' title='Bỏ Thích' type='unlike'><img class='like strech' src='icon/7.png' width='15px' height='15px' />Bỏ Thích</a>";
									} else {
										contentre += "				<div class='likecomment'><a href='#' class='status-post-likess' title='Thích' type='like'><img class='like strech' src='icon/7.png' width='15px' height='15px' />Thích</a>";
									}
									
									if(status.getStatuslikes().size() > 0) {
										likmember = likmember.substring(0, likmember.length() - 1);
									}
									contentre += likmember;
									contentre += "					</div><hr /><div class='comment-containt-post'>";
									for(CommentStatus st : status.getCommentstatuses()) {
										contentre += "				<div class='friend-comment friendcommentstatus-post-id-" + st.getIdcomstatus() + "' idcommentstatus='" + st.getIdcomstatus() + "'>" +
												"						<div class='friend-avatar' style='background:url(" + st.getAccount().getAvatar() + ") no-repeat; background-size: 100% auto;'></div>" +
														"				<div class='noidungfriend'>";
										if(idacc.equalsIgnoreCase(email)) {
											contentre += "<div class='comment-deleted-commentstatus' iddelecomment='" + st.getIdcomstatus() + "' title='Xóa'>X</div>";
										} else if(email.equalsIgnoreCase(st.getAccount().getEmail())) {
											contentre += "<div class='comment-deleted-commentstatus' iddelecomment='" + st.getIdcomstatus() + "' title='Xóa'>X</div>";
										}
										contentre += "<a href='index.jsp?acc=" + st.getAccount().getEmail() + "'><span>" + st.getAccount().getFullname() + "</span></a> " + st.getContent() + "</div>" +
																"	</div>";// danh sach comment
									}
									contentre += "</div><div class='friend-comment'><div class='friend-avatar' style='background:url(" + acclogin.getAvatar() + ") no-repeat; background-size: 100% auto;'></div><div class='noidungfriend'><div class='commentstatus-friend' style='width: 100%; min-height: 40px; border: 1px solid rgb(233, 234, 237); background: #FFF;'><textarea style='width:99%; height:38px; resize: none; outline: none; border: 0px;'></textarea></div></div></div>";
									contentre += "				</div>" +
											"				</div>" +
											"				<div class='post-view-footer'></div>" +
											"			</div>" +
											"		</div>" +
											"	</div>" +
											"	<div class='space'>&nbsp;</div>";
								}
								
								resultnews.add(contentre);
							}
						}
						result = new Gson().toJson(resultnews);
					} else {
						result = new Gson().toJson("noload");
					}
				} else {
					result = new Gson().toJson("null");
				}
			} else {
				result = new Gson().toJson("null");
			}
		} else {
			result = new Gson().toJson("null");
		}
		System.out.println(result);
		return result;
	}
	
	@RequestMapping(value = "accountupdatestatus", method = RequestMethod.POST)
	public @ResponseBody Map<String, String> accountUpdateStatus(HttpServletRequest request, HttpSession session) {
		Map<String, String> result = new HashMap<String, String>();
		String email = (String) session.getAttribute("accountinfo");
		boolean insert = false;
		String idstatus = "";
		String content = null;
		if (email != null) {
			content = request.getParameter("contentre");
			if(content != null && content.trim().length() > 0) {
				content = new Emoticon().replaceEmo(content);
				idstatus = nextID("ST", 20, statusDAO.getIDStatusLast());
				Status status = new Status();
				status.setIdstatus(idstatus);
				Account account = new Account();
				account.setEmail(email);
				status.setAccount(account);
				status.setContent(content);
				status.setDatecreate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
				insert = statusDAO.insertStatus(status);
				if(insert) {
					String idnew = nextID("", 20, newsInfoDAO.getIDNewInfoLast());
					NewInfo info = new NewInfo();
					info.setId(idnew);
					info.setEmail(email);
					info.setIdtable(idstatus);
					info.setNametable("status");
					info.setDatecreate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
					insert = newsInfoDAO.insertNewInfo(info);
					
					Account acc = new AccountDAO().getAccountInfoByComment(email);
					
					Notificate.sendBroadcast("noti\0status\0news\0" + email + "\0" + acc.getFullname() + "\0" + acc.getAvatar() + "\0Vừa đăng bài mới lên tường của bạn ấy");
					
				}
			}
		}
		
		if(insert) {
			result.put("result", "true");
			result.put("id", idstatus);
			result.put("content", content);
		} else {
			result.put("result", "false");
		}
		return result;
	}
	
	@RequestMapping(value = "ajaxaccountcommentstatus", method = RequestMethod.POST)
	public @ResponseBody Map<String, String> accountcommentstatus(HttpServletRequest request, HttpSession session) {
		Map<String, String> result = new HashMap<String, String>();
		String email = (String) session.getAttribute("accountinfo");
		boolean insert = false;
		String idstatuscom = "";
		String content = null;
		System.out.println(email);
		if (email != null) {
			content = request.getParameter("contentre");
			String idstatus = request.getParameter("id");
			if(content != null && idstatus != null) {
				content = new Emoticon().replaceEmo(content);
				idstatuscom = nextID("", 20, commentStatusDAO.getIDStatusCommentLast());
				CommentStatus status = new CommentStatus();
				status.setIdcomstatus(idstatuscom);
				Status st = new Status();
				st.setIdstatus(idstatus);
				status.setStatus(st);
				Account account = new Account();
				account.setEmail(email);
				status.setAccount(account);
				status.setContent(content);
				status.setCommentdate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
				
				insert = commentStatusDAO.insertCommentStatus(status);
				
				if(insert) {
					ArrayList<String> emaillikethongbao = statusDAO.getEmailCommentStatus(idstatus);
					Account acc = accountDAO.getAccountInfoByComment(email);
					Account nguoidangstatus = statusDAO.getNameAccountNewStatus(idstatus);
					if(!nguoidangstatus.getEmail().equals(email)) {
						Notificate.sendPrivate(nguoidangstatus.getEmail(), "noti\0status\0like\0" + email + "\0" + acc.getFullname() + "\0" + acc.getAvatar() + "\0Vừa bình luận trạng thái của bạn");
					}
					for(String emaillike : emaillikethongbao) {
						if(!email.equals(emaillike)) {
							Notificate.sendPrivate(emaillike, "noti\0status\0like\0" + email + "\0" + acc.getFullname() + "\0" + acc.getAvatar() + "\0Vừa bình luận trạng thái của <a href='index.jsp?acc=" + nguoidangstatus.getEmail() + "'>" + nguoidangstatus.getFullname() + "</a>");
						}
					}
				}
			}
		}
		
		if(insert) {
			result.put("result", "true");
			result.put("idstatuscom", idstatuscom);
			result.put("contentcom", content);
		} else {
			result.put("result", "false");
		}
		return result;
	}
	
	@RequestMapping(value = "ajaxdeletecommentstatusacc", method = RequestMethod.POST)
	public @ResponseBody boolean ajaxDeleteCommentStatus(HttpServletRequest request, HttpSession session) {
		boolean result = false;
		
		String email = (String) session.getAttribute("accountinfo");
		if (email != null) {
			String idcomment = request.getParameter("idcommentre");
			if(idcomment != null) {
				result = commentStatusDAO.deleteCommentStatus(idcomment);
			}
		}
		
		return result;
	}
	
	//ajaxdeletestatusacc
	@RequestMapping(value = "ajaxdeletestatusacc", method = RequestMethod.POST)
	public @ResponseBody boolean ajaxDeleteStatus(HttpServletRequest request, HttpSession session) {
		boolean result = false;
		
		String email = (String) session.getAttribute("accountinfo");
		if (email != null) {
			String idcomment = request.getParameter("idstatusre");
			String type = request.getParameter("typere");
			if(idcomment != null && type != null) {
				result = newsInfoDAO.deleteNewInfo(idcomment, email, type);
			}
		}
		
		return result;
	}
	
	@RequestMapping(value = "ajaxlikestatuspostacc", method = RequestMethod.POST)
	public @ResponseBody boolean likeStatusPostAcc(HttpServletRequest request, HttpSession session) {
		boolean result = false;
		
		String email = (String) session.getAttribute("accountinfo");
		if (email != null) {
			String idcomment = request.getParameter("idstatusre");
			String type = request.getParameter("typere");
			if(idcomment != null && type != null) {
				if(type.equalsIgnoreCase("like")) {
					// like status
					result = statusDAO.insertStatusLike(idcomment, email, new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
					
					if(result) {
						ArrayList<String> emaillikethongbao = statusDAO.getEmailCommentStatus(idcomment);
						Account acc = accountDAO.getAccountInfoByComment(email);
						Account nguoidangstatus = statusDAO.getNameAccountNewStatus(idcomment);
						if(!nguoidangstatus.getEmail().equals(email)) {
							Notificate.sendPrivate(nguoidangstatus.getEmail(), "noti\0status\0like\0" + email + "\0" + acc.getFullname() + "\0" + acc.getAvatar() + "\0Vừa thích trạng thái của bạn");
						}
						for(String emaillike : emaillikethongbao) {
							if(!nguoidangstatus.getEmail().equals(emaillike)) {
								Notificate.sendPrivate(emaillike, "noti\0status\0like\0" + email + "\0" + acc.getFullname() + "\0" + acc.getAvatar() + "\0Vừa thích trạng thái của <a href='index.jsp?acc=" + nguoidangstatus.getEmail() + "'>" + nguoidangstatus.getFullname() + "</a>");
							}
						}
					}
				} else if(type.equalsIgnoreCase("unlike")) {
					// unlike status
					result = statusDAO.deleteStatusLike(idcomment, email);
				}
			}
		}
		
		return result;
	}
	
	/**
	 * next id
	 * @param sStart
	 * @param lenght
	 * @param sLast
	 * @return
	 */
	public String nextID(String sStart, int lenght, String sLast) {
		String result = sStart;
		
		if (sLast.length() > 0) {
			String temp = sLast.substring(sStart.length());
			int number = Integer.parseInt(temp) + 1;
			int numlenght = (number + "").length();
			for(int i = (sStart.length() + numlenght); i < lenght; i++) {
				result += "0";
			}
			result += number;
		} else {
			for(int i = (sStart.length() + 1); i < lenght; i++) {
				result += "0";
			}
			result += "1";
		}
		
		return result;
	}
	
}
