package com.atlassian.stash.internal.web.soy.functions;

import com.atlassian.bitbucket.util.DateFormatter;
import com.atlassian.soy.renderer.JsExpression;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Date;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class FormatDateFunctionTest {

    @Mock
    private DateFormatter dateFormatter;

    @Mock(answer = Answers.RETURNS_DEFAULTS)
    private FormatDateFunction function;

    @Before
    public void setUp() throws Exception {
        function = new FormatDateFunction(dateFormatter);
    }

    @Test
    public void testApplyWithValidArguments() throws Exception {
        function.apply(0, DateFormatter.FormatType.SHORT.name());
        verify(dateFormatter).formatDate(new Date(0), DateFormatter.FormatType.SHORT);
        verifyNoMoreInteractions(dateFormatter);
        reset(dateFormatter);

        function.apply(new Date(0), DateFormatter.FormatType.LONG.name());
        verify(dateFormatter).formatDate(new Date(0), DateFormatter.FormatType.LONG);
        verifyNoMoreInteractions(dateFormatter);
        reset(dateFormatter);

        function.apply(new Date(0), DateFormatter.FormatType.LONG.name().toLowerCase());
        verify(dateFormatter).formatDate(new Date(0), DateFormatter.FormatType.LONG);
        verifyNoMoreInteractions(dateFormatter);
        reset(dateFormatter);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testApplyWithInvalidFormatType() throws Exception {
        function.apply(0, "my cool format");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testApplyWithInvalidDate() throws Exception {
        function.apply("", "my cool format");
    }

    @Test
    public void testGenerate() throws Exception {
        final JsExpression generated = function.generate(new JsExpression("someDate"), new JsExpression("someFormatType"));
        assertNotNull(generated);
        assertEquals("require('bitbucket/internal/util/time').format(someDate, someFormatType)", generated.getText());
    }
}
