/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.spring;

import java.util.HashMap;
import java.util.Map;

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

import org.bodington.server.BuildingSession;
import org.bodington.server.Quota;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class QuotaController extends SimpleFormController implements Validator
{
    public QuotaController()
    {
        setCommandClass(QuotaForm.class);
    }
    
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
    {
        // Map numbers to Longs but allow them to be empty.
        binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, true));
    }

    protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception
    {
        BuildingSession session = Utils.getSession(request);
        Map model = new HashMap();
        model.put("files", session.getUploadedFileSession().getQuota());
        model.put("resources", session.getQuota());

        return model;
    }
    
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
    throws Exception
    {
        QuotaForm form = (QuotaForm)command;
        BuildingSession session = Utils.getSession(request);
        if (form.getFile() == null && form.getResource() == null)
        {
            Utils.saveMessage(request, getMessageSourceAccessor().getMessage("nothing.done.as.empty"));
        }
        if (form.getFile() != null)
        {
            session.getUploadedFileSession().setQuota(form.getFile().longValue());
            Utils.saveMessage(request,
                getMessageSourceAccessor().getMessage("files.quota.set",
                    new Object[]{form.getFile()}));
        }
        if (form.getResource() != null)
        {
            session.setQuota(form.getResource().longValue());
            Utils.saveMessage(request,
                getMessageSourceAccessor().getMessage("resources.quota.set",
                    new Object[]{form.getResource()}));
        }
        return showForm(request, response, errors, referenceData(request, command, errors));
    }
    
    protected Object formBackingObject(HttpServletRequest request) throws Exception
    {
        QuotaForm command = (QuotaForm)createCommand();
        BuildingSession session = Utils.getSession(request);
        Quota fileQuota = session.getUploadedFileSession().getQuota();
        if (fileQuota != null && session.getResourceId().equals(fileQuota.getResource().getResourceId()))
            command.setFile(new Long(fileQuota.getQuota()));
        Quota resourceQuota = session.getQuota();
        if (resourceQuota != null && session.getResourceId().equals(resourceQuota.getResource().getResourceId()))
            command.setResource(new Long(resourceQuota.getQuota()));
        return command;
    }

    public boolean supports(Class clazz)
    {
        return QuotaForm.class.isAssignableFrom(clazz);
    }

    public void validate(Object obj, Errors errors)
    {
        if (obj instanceof QuotaForm)
        {
            QuotaForm form = (QuotaForm) obj;
            if ( form.getFile() != null && form.getFile().longValue() < 0 )
                errors.rejectValue("file", "error.0.or.more");
            if ( form.getResource() != null && form.getResource().longValue() < 1 )
                errors.rejectValue("resource", "error.1.or.more");
            
        }
        
    }
}
