package zall.action.media;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Logger;

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;
import zutil.log.LogUtil;

public class CreateFolderAction extends ZalleryAction{
	private static final Logger logger = LogUtil.getLogger();

	public CreateFolderAction() {
		super("mkdir", true);
	}

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

		// Create Folder
		String path = request.getParameter("dir");
		Folder folder = Folder.load(db, path, user);
		logger.info( "Creating new folder: /"+user.getName()+"/"+path );
		// parent folder
		if( folder == null ){
			String[] dirs = path.split("/");
			Folder parent = Folder.loadRoot(db, user);
			if( user.isSuperUser() && path.charAt(0) == '/' )
				path = "";
			else{
				path = "/{NAME}";

				// Get root folder
				parent = Folder.load(db, path, user); // Get user root folder
				if( parent == null ){ // Create root folder
					parent = Folder.loadRoot(db, user); // get root folder
					folder = new Folder();
					folder.setUser( user );
					folder.setParent( parent );
					folder.setName( "{NAME}" );
					folder.save( db );
					parent = folder;
				}
			}

			for(String dir : dirs){
				if( dir.trim().isEmpty() ) // skip empty names
					continue;
				path += "/"+dir;
				folder = Folder.load(db, path, user);
				if(folder == null){ // create folder
					folder = new Folder();
					folder.setUser( user );
					folder.setParent( parent );
					folder.setName( dir );
					folder.save( db );
				}
				parent = folder;
			}
			if(out != null)	out.print( "{\"id\":"+folder.getId()+", \"name\":\""+folder.getPath()+"\"}" );
			else			msgs.add(MessageType.INFO, "Folder '"+path+"' has been successfully created.!");
		}
		else if(out != null)	out.println("{\"error\":\"The folder '"+path+"' already exists!\"}");
		else					msgs.add(MessageType.ERROR, "The folder '"+path+"' already exists!");
		return;
	}

}
