package it.com.atlassian.stash.admin;

import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.webdriver.bitbucket.page.UserAccountSettingsPage;
import com.atlassian.webdriver.bitbucket.page.admin.AdminHomePage;
import com.atlassian.webdriver.bitbucket.page.admin.AvatarSettingsPage;
import com.jayway.restassured.RestAssured;
import it.com.atlassian.stash.BaseBrowserFuncTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static javax.ws.rs.core.Response.Status.OK;

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

public class AvatarSettingsTest extends BaseBrowserFuncTest {
    private boolean gravatarEnabled = false;

    @Before
    public void captureGravatarSettings() {
        gravatarEnabled = loginAsAdmin(AdminHomePage.class).gotoAvatarPage().isGravatarEnabled();
    }

    @After
    public void restoreGravatarSettings() {
        loginAsAdmin(AdminHomePage.class).gotoAvatarPage().setGravatarEnabled(gravatarEnabled).clickSave();
    }

    @Test
    public void testCanToggleGravatarSetting() {
        AvatarSettingsPage avatarPage = loginAsAdmin(AdminHomePage.class).gotoAvatarPage();

        avatarPage.setGravatarEnabled(true);
        assertTrue("Gravatar should now be enabled", avatarPage.clickSave().isGravatarEnabled());
        assertUpdated(avatarPage);

        assertThat(BITBUCKET.visit(UserAccountSettingsPage.class).getAvatarUrl(), containsString("gravatar.com"));

        avatarPage = BITBUCKET.visit(AvatarSettingsPage.class);
        avatarPage.setGravatarEnabled(false);
        assertFalse("Gravatar should now be disabled", avatarPage.clickSave().isGravatarEnabled());
        assertUpdated(avatarPage);

        String avatarUrl = BITBUCKET.visit(UserAccountSettingsPage.class).getAvatarUrl();
        assertThat(avatarUrl, not(containsString("gravatar.com")));

        RestAssured.given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .expect().statusCode(OK.getStatusCode()).contentType("image/png")
                .when().get(avatarUrl);
    }

    private void assertUpdated(AvatarSettingsPage avatarPage) {
        assertThat(avatarPage.getAuiSuccessMessages(), hasItem("The avatar settings were updated"));
    }
}
