package zall.action.media;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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

import zall.action.ZalleryAction;
import zall.bean.Media;
import zall.bean.User;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;

public class ModifyMediaAction extends ZalleryAction{

	public ModifyMediaAction() {
		super("modmedia", true);
	}

	@Override
	public void handleRequest(DBConnection db, HttpServletRequest request, HttpServletResponse response, HttpSession session,
			PrintWriter out, User user, UserMessage msgs) throws SQLException, IOException {

		// Edit media information
		if( request.getParameter("id") == null || request.getParameter("type") == null ){
			if(out != null)	out.println("{ \"error\": \"Missing parameters!\"}");
			else			msgs.add(MessageType.ERROR, "Missing parameters!");
			return;
		}
		long id =  Long.parseLong(request.getParameter("id"));
		Media media = Media.load(db, request.getParameter("type"), id);
							
		if( media != null ){
			if( user.canEdit(media) ){
				media.setTitle( request.getParameter("title") );
				media.setDescription( request.getParameter("description") );
				media.save(db);
				
				if(out != null)	out.println("{}");
				else			msgs.add(MessageType.INFO, "Item edited successfully.");
			}
			else if(out != null)	out.println("{ \"error\": \"You are not authorize to modify this item!\"}");
			else					msgs.add(MessageType.ERROR, "You are not authorize to modify this item!");
		}
		else if(out != null)	out.println("{ \"error\": \"No such item!\"}");
		else					msgs.add(MessageType.ERROR, "The item does not exist!");

	}

}
