package it.com.atlassian.stash.readme;

import com.atlassian.bitbucket.test.ReadmeRepoRule;
import com.atlassian.webdriver.bitbucket.page.FileLayoutPage;
import com.atlassian.webdriver.bitbucket.page.readme.FileBrowserReadmePage;
import it.com.atlassian.stash.BaseBrowserFuncTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.By;

import static org.junit.Assert.assertEquals;

public class ReadmeTest extends BaseBrowserFuncTest {

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

    private FileBrowserReadmePage login() {
        return loginAsAdmin(FileBrowserReadmePage.class, readme.project, readme.repo);
    }

    @Test
    public void testTopLevelReadme() {
        FileBrowserReadmePage page = login();
        assertEquals("test2", page.getReadme().getReadmeHtml());
        assertEquals("README.md", page.getReadme().getReadmeTitle());
    }

    @Test
    public void testTopLevelReadmeBranch() {
        FileBrowserReadmePage page = login();
        page.getBranchSelector().open().selectItemById("refs/heads/first");
        assertEquals("test", page.getReadme().getReadmeHtml());
    }

    @Test
    public void testSubFolderReadme() {
        FileBrowserReadmePage page = login();
        page.clickFolder("a");
        assertEquals("testa", page.getReadme().getReadmeHtml());
    }

    @Test
    public void testSubFolderNoReadme() {
        FileBrowserReadmePage page = login();
        page.clickFolder("b");
        page.getReadme().waitUntilNotVisible();
    }

    @Test
    public void testViewFile() {
        ReadmeSourcePage page = loginAsAdmin(ReadmeSourcePage.class, readme.project, readme.repo, "README.md");
        assertEquals("test2", page.getHtml());
    }

    // No one else really needs this, so keep it here for now
    // Extending FileSourcePage is too much work
    public static class ReadmeSourcePage extends FileLayoutPage {

        public ReadmeSourcePage(String projectKey, String repoSlug, String path) {
            super(projectKey, repoSlug, path);
        }

        @Override
        protected String getPathComponent() {
            return "browse";
        }

        public String getHtml() {
            return body.find(By.className("markup-content")).getText();
        }
    }
}
