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.Folder;
import zall.bean.User;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;

public class RemoveFolderAction extends ZalleryAction{

	public RemoveFolderAction() {
		super("rmdir", true);
	}

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

		//Remove Media
		if( request.getParameter("id") == null){
			if(out != null)	out.println("{ \"error\": \"Missing parameters!\"}");
			else			msgs.add(MessageType.ERROR, "Missing parameters!");
			return;
		}
		long id = Long.parseLong(request.getParameter("id"));
		Folder folder = Folder.load(db, id);

		if( folder != null ){
			if( !folder.isEmpty(db) ){
				if(out != null)	out.println("{ \"error\": \"Folder is not empty!\"}");
				else			msgs.add(MessageType.ERROR, "Folder is not empty!");
			} else if( user.canEdit(folder) ){
				folder.delete( db );
				if(out != null)	out.println("{}");
				else			msgs.add(MessageType.INFO, "Folder removed successfully.");
			}
			else if(out != null)	out.println("{ \"error\": \"You are not authorize to delete this folder!\"}");
			else					msgs.add(MessageType.ERROR, "You are not authorize to delete this folder!");
		}
		else if(out != null)	out.println("{ \"error\": \"No such folder!\"}");
		else					msgs.add(MessageType.ERROR, "The folder does not exist!");

	}

}
