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

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.mynonglam.dao.ProfilePictureMod;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Controller
public class ChangeProfilePicture {
	
	@Autowired
	private ProfilePictureMod ppMod;

	
	@RequestMapping(value = "changeAvatarX", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public @ResponseBody String changeAvatarX(HttpServletRequest request) throws UnsupportedEncodingException, SQLException {
		HttpSession session = request.getSession();
		String email = (String)session.getAttribute("accountinfo");
		String link = request.getParameter("avatar");
		ppMod.changeAvatar(email, link);
		return "";
	}
	
	@RequestMapping(value = "changeCoverX", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public @ResponseBody String changeCoverX(HttpServletRequest request) throws UnsupportedEncodingException, SQLException {
		HttpSession session = request.getSession();
		String email = (String)session.getAttribute("accountinfo");
		String link = request.getParameter("cover");
		ppMod.changeCover(email, link);
		return "";
	}

	@RequestMapping(value = "getMyImagesX", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public @ResponseBody String getMsgOffline(HttpServletRequest request) throws UnsupportedEncodingException, SQLException {
		HttpSession session = request.getSession();
		String email = (String)session.getAttribute("accountinfo");

		// LIMIT AND OFFSET
		int limit = 16;
		int offset = Integer.parseInt(request.getParameter("offset"));
		
			// INIT
		if (offset == 0) {
			offset = ppMod.getImagesRecordNumber(email) - limit;
			// OVERFLOW
			if (offset < 0) offset = 0;
		} 
			// LOAD MORE
		else if (offset <= limit) {
			limit = offset;
			offset = 0;
		} else {
			offset = offset - limit;
		}

			
		// END
		
		ArrayList<String> list = ppMod.getImages(email, offset, limit);
		if (list.size() == 16) {
			list.remove(0);
			list.add(0, "" + offset);
		}
		return new Gson().toJson(list);
	}
}
