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.manager.AuthenticationManager;
import zutil.db.DBConnection;
import zutil.ui.UserMessageManager;
import zutil.ui.UserMessageManager.MessageLevel;
import zutil.ui.UserMessageManager.UserMessage;

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, UserMessageManager msgs) throws SQLException, IOException {

        //Remove Media
        if (request.getParameter("id") == null) {
            msgs.add(new UserMessage(MessageLevel.ERROR, "Missing parameters!"));
            return;
        }
        long id = Long.parseLong(request.getParameter("id"));
        Folder folder = Folder.load(db, id);

        if (folder != null) {
            if (!folder.isEmpty(db)) {
                msgs.add(new UserMessage(MessageLevel.ERROR, "Folder is not empty!"));
            } else if (AuthenticationManager.canEdit(user, folder)) {
                folder.delete(db);
                msgs.add(new UserMessage(MessageLevel.INFO, "Folder removed successfully."));
            } else
                msgs.add(new UserMessage(MessageLevel.ERROR, "You are not authorize to delete this folder!"));
        } else
            msgs.add(new UserMessage(MessageLevel.ERROR, "The folder does not exist!"));

    }

}
