package com.atlassian.webdriver.bitbucket.page;


import com.atlassian.crowd.embedded.impl.IdentifierUtils;
import org.openqa.selenium.By;
import org.springframework.web.util.UriUtils;

import java.io.UnsupportedEncodingException;
import java.text.Normalizer;

public class UserProfilePage extends BitbucketPage {
    private String slug;

    public UserProfilePage(String slug) {
        this.slug = slug;
    }

    @Override
    public String getUrl() {
        return "/users/" + encodedSlug();
    }

    private String encodedSlug() {
        try {
            String encoded = UriUtils.encodePathSegment(slugify(slug), "UTF-8");
            //hack: specially encode ' even though it is a legal sub-delimeter. something seems to be encoding
            //it so if we don't mimic it, we will not match on the browser URL
            encoded = encoded.replace("\'", "%27");
            return encoded;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private String slugify(String username) {
        //Copied from InternalStashUser.slugify - alas no code sharing possible here
        String slug = IdentifierUtils.toLowerCase(username);
        slug = Normalizer.normalize(slug, Normalizer.Form.NFKD);
        slug = slug.replace("/", "%2f").replace("\\", "%5c");
        return slug;
    }

    public String getDisplayName() {
        return driver.findElement(By.cssSelector("header .entity-name")).getText();
    }

    public String getUsername() {
        return driver.findElement(By.cssSelector("header .user-detail.username")).getText();
    }

    public String getEmail() {
        return driver.findElement(By.cssSelector("header .user-detail.email")).getText();
    }

    public UserProfileRepositoriesTabPage clickRepositoriesTab() {
        driver.findElement(By.id("repositories-tab")).click();
        return pageBinder.bind(UserProfileRepositoriesTabPage.class, slug);
    }

    public UserProfileRepositoriesTabPage showRepositoriesTab() {
        if (driver.findElements(By.className("menu-item")).size() == 0) {
            //If there are no tabs, the repo list is already shown, so don't try and click the tab.
            return pageBinder.bind(UserProfileRepositoriesTabPage.class, slug);
        } else {
            return clickRepositoriesTab();
        }
    }
}
