package it.com.atlassian.stash.rest.readme;

import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.bitbucket.test.ReadmeRepoRule;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import it.com.atlassian.stash.BaseRestTest;
import org.hamcrest.Matcher;
import org.junit.ClassRule;
import org.junit.Test;

import static org.hamcrest.Matchers.*;

public class ReadmeResourceTest extends BaseRestTest {

    @ClassRule
    public static ReadmeRepoRule readme = new ReadmeRepoRule();

    @Test
    public void testReadme() throws Exception {
        expectReadme("<h1>test2</h1>\n", "README.md");
    }

    @Test
    public void testBinary() throws Exception {
        // The CommonMark spec requires U+0000 to be replaced by replacement character (U+FFFD)
        expectReadme("<h1>test\uFFFD</h1>\n", "binary/README.md");
    }

    @Test
    public void testUnicode() throws Exception {
        expectReadme("<h1>H&auml;ll&ouml; \uD83D\uDE00</h1>\n", "unicode/README.md");
    }

    @Test
    public void testUnknownType() throws Exception {
        expectReadme(notNullValue(), "js/README.js", equalTo(null), 415);
    }

    @Test
    public void testReadmeBranch() throws Exception {
        expectReadme("<h1>test</h1>\n", "README.md?at=first");
    }

    @Test
    public void testReadmeSubfolder() throws Exception {
        expectReadme("<h1>testa</h1>\n", "a/readme.md");
    }

    @Test
    public void testReadmeSubfolderEmpty() throws Exception {
        expectReadme(notNullValue(), "b/notfound.txt", equalTo("no-cache, no-transform"), 404);
    }

    @Test
    public void testReadmeCache() throws Exception {
        expectReadme(equalTo("<h1>test2</h1>\n"), "README.md?blob=0bb059126d4ca9894e3ad7003ad2688b67494e4a", containsString("max-age="), 200);
    }

    private Response expectReadme(String content, String file) {
        return expectReadme(equalTo(content), file, equalTo("no-cache, no-transform"), 200);
    }

    private Response expectReadme(Matcher content, String file, Matcher cache, int status) {
        return RestAssured.given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .expect().content(content).statusCode(status).headers("Cache-Control", cache)
                .get(createUrl(file));
    }

    private String createUrl(String file) {
        return DefaultFuncTestData.getRestURL("readme", "latest") + String.format("/projects/%s/repos/%s/markup/%s", readme.project, readme.repo, file);
    }

}
