package org.springframework.samples.petclinic.web;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.springframework.samples.petclinic.web.ViewUtils.PET_OBJ_NAME;

import java.util.HashMap;

import org.junit.Before;
import org.junit.Test;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.validation.PetValidator;
import org.springframework.validation.Errors;
import org.springframework.validation.MapBindingResult;

/**
 * Unit tests for {@link PetValidator}
 * 
 * @author Chris Beams
 */
public class PetValidatorTests {

    private PetValidator validator;
    private Errors errors;


    @Before
    public void setUp() {
        validator = new PetValidator();
        errors = new MapBindingResult(new HashMap<Object, Object>(), PET_OBJ_NAME);
    }

    @Test
    public void petWithValidName() {
        Pet fido = new Pet();
        fido.setName("fido");

        Owner fidoOwner = new Owner();
        fidoOwner.addPet(fido);

        validator.validate(fido, errors);

        assertFalse(errors.hasErrors());
    }

    @Test
    public void petWithInvalidName() {
        Pet fido = new Pet();
        fido.setName(""); // invalid!

        Owner fidoOwner = new Owner();
        fidoOwner.addPet(fido);

        validator.validate(fido, errors);

        assertTrue(errors.hasErrors());
    }

    @Test
    public void duplicatePet() {
        Owner fidoOwner = new Owner();

        { // add first 'fido' pet
            Pet original = new Pet();
            original.setName("fido");
            original.setId(1);
            fidoOwner.addPet(original);
        }

        { // add second, duplicate 'fido'
            Pet duplicate = new Pet();
            duplicate.setName("fido");
            fidoOwner.addPet(duplicate);
            validator.validate(duplicate, errors);
            assertTrue(errors.hasErrors());
        }
    }
}
