package tryslim3.controller.crud2;

import java.util.logging.Logger;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.util.BeanUtil;

import tryslim3.meta.Crud2Meta;
import tryslim3.model.Crud2;
import tryslim3.service.Crud2Service;

public class InsertController extends Controller {
    private static final Logger logger =
        Logger.getLogger(IndexController.class.getName());

    private Crud2Service service = new Crud2Service();

    private Crud2Meta meta = Crud2Meta.get();

    @Override
    public Navigation run() throws Exception {
        if (!validate()) {
            return forward("create");
        }
        Crud2 crud2 = new Crud2();
        BeanUtil.copy(request, crud2);
        logger.info(ToStringBuilder.reflectionToString(crud2));
        service.insert(crud2);
        return redirect(basePath);
    }

    protected boolean validate() {
        Validators v = new Validators(request);
        v.add(meta.title, v.required());
        v.add(meta.content, v.required());
        return v.validate();
    }
}