package zall;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

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

import org.apache.commons.fileupload.FileItem;

import zall.bean.Folder;
import zall.bean.Image;
import zall.bean.User;
import zall.bean.Video;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.jee.upload.AjaxFileUpload;
import zutil.log.LogUtil;


public class UploadServlet extends AjaxFileUpload{
	private static final Logger logger = LogUtil.getLogger();
	private static final long serialVersionUID = 1L;
	
	private static final Set<String> VIDEO_EXT = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
	        "avi","mp4","mpeg","mpeg","divx","xvid","wmv","mov","flv","m4v")));

	@Override
	public String getProgressHTML() {
		return ""+ 
				"<DIV class='comment-author vcard'>"+
				"	<IMG src='img/upload.png' class='photo avatar photo' height='80' width='80'>"+
				"	<SPAN class='fn n'>"+
				"		<span class='status'>Unknown</span>: <span class='filename' style='font-weight: normal;'>Unknown</span> - <span class='message' style='font-weight: normal;'>Unknown</span>"+
				"		<div class='progressbar'>"+
				"			<b class='progress' style='width: 0%'>	</b>"+
				"		</div>"+
				"	</SPAN>"+
				"</DIV>"+
				"<DIV class='comment-meta'>" +
				"	<span class='uploaded'>0 KB</span>/ <span class='total'>0 KB</span> " +
				"	- Speed: <span class='speed'>400 KB/s</span>" +
				"</DIV> ";
	}

	@Override
	public void doUpload(HttpServletRequest request, HttpServletResponse response,
			Map<String,String> fields, List<FileItem> files) throws ServletException{
		DBConnection db = null;
		try {
			HttpSession session = request.getSession();
			db = Zallery.getDB();
			User user = (User) session.getAttribute("user");

			// Check if user is authentication
			if(user != null){
				Folder folder = Folder.load(db, Long.parseLong( fields.get("folder") ));

				// Handle files
				for(FileItem item : files){
					try{
						String ext = FileUtil.getFileExtension(item.getName()).toLowerCase();
						if( VIDEO_EXT.contains(ext) ){
							Video vid = new Video();
							vid.setTitle( item.getName() );
							vid.setFolder( folder );
							vid.setUser( user );
							vid.setFile( item );
							vid.save(db);
							logger.info("Video upload successful: "+vid.getFolder().getPath());
						}
						else{							
							Image img = new Image();
							img.setTitle( item.getName() );
							img.setFolder( folder );
							img.setUser( user );
							img.setFile( item );
							img.save(db);
							logger.info("Image upload successful: "+img.getFolder().getPath());
						}
					} catch (Exception e) {
						logger.log(Level.WARNING, "Error: Creating new Media(\""+item.getName()+"\")", e);
						e.printStackTrace();
					}
					item.delete();
				}
				response.getWriter().print("<html>OK</html>");
			}
			else
				response.getWriter().print("<html>Authentication Error</html>");
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		} finally{
			if(db != null) db.close();
		}
	}

}
