package it.com.atlassian.stash;

import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.bitbucket.test.ClasspathResourceRule;
import com.atlassian.bitbucket.test.ProjectTestHelper;
import com.atlassian.webdriver.bitbucket.element.AvatarPickerDialog;
import com.atlassian.webdriver.bitbucket.page.ProjectCreatePage;
import org.junit.ClassRule;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ProjectAvatarPickerTest extends BaseBrowserFuncTest {

    private static final String AVATAR_PNG = "/com/atlassian/stash/test/avatar/test-avatar.png";
    private static final String TEXT_FILE = "/com/atlassian/stash/test/avatar/test-text-file.txt";

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

    @Test
    public void testCreateProjectWithAvatar() throws Exception {
        ProjectCreatePage page = loginAsAdmin(ProjectCreatePage.class);
        assertFalse(page.hasNonDefaultAvatar());
        page.setKey("APT")
            .setName("Avatar Picker Test")
            .setDescription("Avatar picker test description")
            .setAvatar(getAvatarFile(AVATAR_PNG));
        assertTrue("Non-default project avatar should be selected", page.hasNonDefaultAvatar());
        ProjectTestHelper.deleteProject(page.submitSuccess().getProjectKey());
    }

    @Test
    public void testUploadInvalidImage() throws Exception {
        ProjectCreatePage page = loginAsAdmin(ProjectCreatePage.class);
        AvatarPickerDialog avatarDialog = page.openAvatarPicker();

        avatarDialog.uploadImage(getAvatarFile(TEXT_FILE));
        assertTrue("Should have error uploading non-image file type", avatarDialog.hasErrors());
        Poller.waitUntilTrue(avatarDialog.isImageEmpty());

        avatarDialog.uploadImage(getAvatarFile(AVATAR_PNG));
        assertFalse("Error should have cleared", avatarDialog.hasErrors());
        Poller.waitUntilFalse(avatarDialog.isImageEmpty());
    }

    private String getAvatarFile(String fileName) throws IOException {
        return resources.get(fileName).getPath();
    }

}
