package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import org.openqa.selenium.By;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class UserOption extends IdOption {

    public static final Function<UserOption, String> TO_DISPLAY_NAME = new Function<UserOption, String>() {
        @Override
        public String apply(UserOption option) {
            return option.getDisplayName();
        }
    };

    public static final Function<UserOption, String> TO_USERNAME = new Function<UserOption, String>() {
        @Override
        public String apply(UserOption option) {
            return option.getUsername();
        }
    };

    public UserOption(PageElement container) {
        super(container);
    }

    @Nonnull
    public static Predicate<UserOption> usernameMatches(@Nonnull final String username) {
        return idMatches(UserOption.class, username);
    }

    @Nullable
    public String getDisplayName() {
        return container.find(By.className("avatar-with-name")).getAttribute("title");
    }

    @Nullable
    @Override
    public String getId() {
        return getUsername();
    }

    @Nullable
    public String getUsername() {
        return getUsernameContainer().getAttribute("data-username");
    }

    @Nonnull
    protected PageElement getUsernameContainer() {
        return container.find(By.className(Avatar.CLASS_NAME));
    }

    @Override
    protected void extendToString(Objects.ToStringHelper toStringHelper) {
        toStringHelper
                .add("username", getUsername())
                .add("displayName", getDisplayName());
    }
}
