package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.WebDriverLocatable;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import org.openqa.selenium.By;

import javax.annotation.Nonnull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GlobalRepositoryTable extends RepositoryTable<GlobalRepositoryTable.GlobalRepositoryRow> {

    public GlobalRepositoryTable(@Nonnull PageElement pageElement) {
        super(pageElement, GlobalRepositoryRow.class);
    }

    public GlobalRepositoryTable(By locator, TimeoutType timeoutType) {
        super(locator, timeoutType);
    }

    public static class GlobalRepositoryRow extends RepositoryTable.RepositoryRow {

        private static final Pattern PROJECT_URL = Pattern.compile("/projects/([^/]+)");

        @SuppressWarnings("UnusedDeclaration")
        public GlobalRepositoryRow(By locator, TimeoutType timeoutType) {
            super(locator, timeoutType);
        }

        @SuppressWarnings("UnusedDeclaration")
        public GlobalRepositoryRow(WebDriverLocatable locatable, TimeoutType timeoutType) {
            super(locatable, timeoutType);
        }

        protected LinkElement getProjectLink() {
            return getNameColumn().find(By.cssSelector(".project-name a"), LinkElement.class);
        }

        public String getProjectKey() {
            Matcher matcher = PROJECT_URL.matcher(getProjectLink().getUrl());
            return matcher.find() ? matcher.group(1) : null;
        }

        public String getProjectName() {
            return getProjectLink().getText();
        }

        @Override
        protected LinkElement getRepositoryLink() {
            return getNameColumn().find(By.cssSelector(".repository-name a"), LinkElement.class);
        }
    }

}
