package com.atlassian.stash.internal.hibernate;

import org.hibernate.CallbackException;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.junit.Test;

import java.io.Serializable;

import static org.junit.Assert.assertFalse;


public class NoEmptyStringsInterceptorTest {

    // has to be in a com.atlassian.stash package to trigger the interceptor
    private static final class TestEntity {
    }

    private static final Object ENTITY = new TestEntity();
    private static final Serializable ID = new Integer(1);
    private static final Object[] STATE_NO_EMPTY_STRINGS = new Object[]{"1", "2", "3", null};
    private static final Object[] STATE_WITH_EMPTY_STRINGS = new Object[]{"1", "", "", null};
    private static final String[] PROPERTY_NAMES = new String[]{"attribute1", "attribute2", "attribute3", "attribute4"};
    private static final Type STRING_TYPE = new StringType();
    private static final Type[] TYPES = new Type[] {new IntegerType(), STRING_TYPE, STRING_TYPE};

    private NoEmptyStringsInterceptor interceptor = new NoEmptyStringsInterceptor();

    @Test
    public void testOnFlushDirtyNoEmptyStrings() throws Exception {
        assertFalse(interceptor.onFlushDirty(ENTITY, ID, STATE_NO_EMPTY_STRINGS, STATE_NO_EMPTY_STRINGS, PROPERTY_NAMES, TYPES));
    }

    @Test(expected = CallbackException.class)
    public void testOnFlushDirtyWithEmptyStrings() throws Exception {
        interceptor.onFlushDirty(ENTITY, ID, STATE_WITH_EMPTY_STRINGS, STATE_NO_EMPTY_STRINGS, PROPERTY_NAMES, TYPES);
    }

    @Test
    public void testOnSaveNoEmptyStrings() throws Exception {
        assertFalse(interceptor.onSave(ENTITY, ID, STATE_NO_EMPTY_STRINGS, PROPERTY_NAMES, TYPES));
    }

    @Test(expected = CallbackException.class)
    public void testOnSaveWithEmptyStrings() throws Exception {
        interceptor.onSave(ENTITY, ID, STATE_WITH_EMPTY_STRINGS, PROPERTY_NAMES, TYPES);
    }

    @Test
    public void testOnSaveNonBitbucketEntitiesAreIgnored() {
        interceptor.onSave(new Object(), ID, STATE_WITH_EMPTY_STRINGS, PROPERTY_NAMES, TYPES);
    }

    @Test
    public void testOnFlushDirtyNonBitbucketEntitiesAreIgnored() {
        interceptor.onFlushDirty(new Object(), ID, STATE_WITH_EMPTY_STRINGS, STATE_NO_EMPTY_STRINGS, PROPERTY_NAMES, TYPES);
    }
}
