package com.frameworkium.integration.wikipedia.pages;

import com.frameworkium.core.ui.annotations.Visible;
import com.frameworkium.core.ui.element.OptimisedStreamTable;
import com.frameworkium.core.ui.pages.BasePage;
import com.frameworkium.core.ui.pages.PageFactory;
import org.openqa.selenium.NotFoundException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;

import java.util.stream.Stream;

/**
 * This page uses OptimisedStreamTable, this is slower than using Lists of
 * WebElements for columns, especially when running over a grid due to the far
 * greater number of page lookups required. This is even worse for StreamTable,
 * but StreamTable copes with a wider variety of Tables.
 *
 * <p>This is a trade-off between readability, maintainability and performance.
 *
 * <p>This approach is great if the table and tests are likely to change often.
 */
public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> {

    @Visible
    @CacheLookup
    @FindBy(css = "table.wikitable") // luckily there's only one
    private OptimisedStreamTable listTable;

    public static EnglishCountiesPage open() {
        return PageFactory.newInstance(EnglishCountiesPage.class,
                "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England");
    }

    public int populationOf(String countyName) {
        String lookupHeader = "County";
        String targetHeader = "Population";
        String population = listTable
                .getCellsByLookup(lookupHeader, countyName, targetHeader)
                .findFirst()
                .orElseThrow(NotFoundException::new)
                .getText()
                .replaceAll(",", "");
        return Integer.parseInt(population);
    }

    public Stream<Integer> densities() {
        return listTable
                .getColumn(e -> e.getText().startsWith("Density"))
                .map(WebElement::getText)
                .map(density -> density.replaceAll(",", ""))
                .map(Integer::parseInt);
    }

}

@@ -262,16 +262,17 @@
 actory;%0A
+%0A
 import o
@@ -436,24 +436,61 @@
 rt.FindBy;%0A%0A
+import java.util.function.Predicate;%0A
 import java.
@@ -1459,70 +1459,270 @@
     
-String lookupHeader = %22County%22;%0A        String
+Predicate%3CWebElement%3E headerLookUp = e -%3E e.getText().trim().equals(%22County%22);%0A        Predicate%3CWebElement%3E lookUpCellMatcher = e -%3E e.getText().trim().equals(countyName);%0A        Predicate%3CWebElement%3E
  target
+Col
 Header
- = 
+Lookup = e -%3E e.getText().trim().startsWith(
 %22Pop
@@ -1729,16 +1729,17 @@
 ulation%22
+)
 ;%0A      
@@ -1808,40 +1808,47 @@
 kup(
-lookupHeader, countyName
+headerLookUp, lookUpCellMatcher
 , target
 Head
@@ -1843,22 +1843,31 @@
 , target
+Col
 Header
+Lookup
 )%0A      

Fix Wikipedia test failure.