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

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.webdriver.bitbucket.util.DateUtils;
import org.openqa.selenium.By;

import javax.annotation.Nonnull;
import java.time.Instant;

public class StateActivityItem extends ActionActivityItem {

    public StateActivityItem(@Nonnull PageElement activityContainer) {
        super(activityContainer);
    }

    @Nonnull
    public static Class<? extends ActivityItem> getType(PageElement element) {
        return getActivityType(element).type;
    }

    @Nonnull
    public String getState() {
        return getActivityState(activityContainer);
    }

    @Nonnull
    public ActivityType getType() {
        return getActivityType(activityContainer);
    }

    @Nonnull
    public static ActivityType getActivityType(PageElement element) {
        for (ActivityType activityType : ActivityType.values()) {
            if (activityType.matches(element)) {
                return activityType;
            }
        }
        throw new AssertionError("Should not happen");
    }

    public enum ActivityType {
        MERGED(MergeActivityItem.class) {
            @Override
            public boolean matches(PageElement activityElement) {
                return "merged".equalsIgnoreCase(getActivityState(activityElement));
            }
        },
        // add more specific states here as necessary
        GENERAL(StateActivityItem.class);

        private final Class<? extends StateActivityItem> type;

        ActivityType(Class<? extends StateActivityItem> type) {
            this.type = type;
        }

        public boolean matches(PageElement activityElement) {
            return true;
        }
    }

    private static String getActivityState(PageElement element) {
        return element.find(By.className("pull-request-state-lozenge")).getText();
    }
}
