package com.atlassian.webdriver.bitbucket.element.activity;

import com.atlassian.pageobjects.PageBinder;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.TimedCondition;
import com.atlassian.webdriver.bitbucket.element.Avatar;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import org.openqa.selenium.By;

import javax.annotation.Nonnull;
import javax.inject.Inject;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.junit.Assert.assertEquals;

public abstract class ActivityItem {

    @Inject
    protected PageBinder pageBinder;

    protected final PageElement activityContainer;

    public ActivityItem(@Nonnull PageElement activityContainer) {
        this.activityContainer = checkNotNull(activityContainer, "activityContainer");
    }

    @Nonnull
    public static Class<? extends ActivityItem> getType(PageElement element) {
        Map<String, Class<? extends ActivityItem>> classes = ImmutableMap.of(
                "general-comment-activity", GeneralCommentActivity.class,
                "diff-comment-activity", DiffLineCommentActivity.class,
                "file-comment-activity", FileCommentActivity.class,
                "reviewers-updated-activity", ReviewerActivityItem.class);

        Set<String> cssClasses = element.getCssClasses().stream()
                .filter(classes::containsKey)
                .collect(Collectors.toSet());

        if (cssClasses.isEmpty()) {
            return StateActivityItem.getType(element);
        }

        assertEquals(1, cssClasses.size());
        return classes.get(Iterators.getOnlyElement(cssClasses.iterator()));
    }

    @Nonnull
    public Avatar getAvatar() {
        return activityContainer.findAll(By.className("user-avatar"), Avatar.class).get(0);
    }

    public TimedCondition isPresent() {
        return activityContainer.timed().isPresent();
    }
}
