package it.com.atlassian.stash.pull;

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.bitbucket.test.ClasspathResourceRule;
import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.webdriver.bitbucket.element.CommentForm;
import com.atlassian.webdriver.bitbucket.page.PullRequestOverviewPage;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.By;

import java.nio.file.Path;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

public class PullRequestCommentAttachmentTest extends BasePullRequestFuncTest {

    private static final String AVATAR_RESOURCE = "/com/atlassian/stash/test/avatar/test-avatar.png";

    @ClassRule
    public static ClasspathResourceRule resources = new ClasspathResourceRule();

    private Path attachmentPath;

    @Before
    public void setUp() throws Exception {
        attachmentPath = resources.get(AVATAR_RESOURCE).toPath();
    }

    @Test
    public void testAttachmentInGeneralComment() {
        PullRequestOverviewPage page = createPullRequestAndLogin(BRANCH_THAT_HAS_SAME_TEXT_FILE_MODIFIED_SRC,
                BRANCH_THAT_HAS_SAME_TEXT_FILE_MODIFIED_TRGT);

        CommentForm commentForm = page.getGeneralCommentForm();

        String initialText = "Initial text";
        commentForm.setText(initialText);

        commentForm.attach(attachmentPath.toString());

        String textAfterAttaching = commentForm.getText();
        assertThat(textAfterAttaching, containsString(initialText));
        assertThat(textAfterAttaching, containsString("attachment:"));

        commentForm.togglePreview();

        String previewContent = commentForm.getPreviewContent();
        assertThat(previewContent, not(containsString("attachment:")));

        PageElement img = commentForm.getPreviewArea().find(By.tagName("img"));
        String imgSrc = img.getAttribute("src");

        String repositoryURL = DefaultFuncTestData.getRepositoryURL(
                page.getProjectKey(), page.getSlug());
        assertThat(imgSrc, startsWith(repositoryURL));

        String attachmentUrlPath = StringUtils.removeStart(imgSrc, repositoryURL);
        assertThat(attachmentUrlPath, containsString("attachments/"));
        assertThat(attachmentUrlPath, containsString(attachmentPath.getFileName().toString()));
    }
}
