package com.intland.codebeamer.functionaltest.page.trackers;

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.ex.UIAssertionError;
import com.google.common.base.Function;
import com.intland.codebeamer.functionaltest.helper.Helper;
import com.intland.codebeamer.functionaltest.page.SubmitWorkItemPage;
import com.intland.codebeamer.functionaltest.page.common.IsPageLoaded;
import com.intland.codebeamer.functionaltest.page.trackers.documentview.CenterPane;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;

import java.util.concurrent.TimeUnit;

import static com.codeborne.selenide.Selenide.*;

/**
 * Copyright by Intland Software
 * <p>
 * All rights reserved.
 * <p>
 * This software is the confidential and proprietary information
 * of Intland Software. ("Confidential Information"). You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Intland.
 */
public class TableViewPage extends TrackerItemListPage {

    public SelenideElement moreMenuLink() {
        return $(By.xpath(".//a[text()='more']/following-sibling::img"));
    }

    private SelenideElement row(String itemLabel, int index) {
        return $(By.xpath("(.//table[@id='trackerItems']/tbody/tr[.//a[contains(., '" + itemLabel + "')]])[" + index + "]"));
    }

    public enum ContextMenuItem {
        EDIT("Edit", SubmitWorkItemPage.class);

        private final String text;
        private final Class<?> pageObjectClass;

        ContextMenuItem(String s, Class<?> pageObjectClass) {
            text = s;
            this.pageObjectClass = pageObjectClass;
        }

        public boolean equalsName(String otherSelector) {
            return (otherSelector == null) ? false : text.equals(otherSelector);
        }

        public String toString() {
            return this.text;
        }
    }

    @Override
    public boolean isPageLoaded() throws UnsupportedOperationException {
        return Helper.doesPageSourceContain("TableViewHotkeys");
    }

    public IsPageLoaded clickOnMoreMenuItem(CenterPane.MoreMenuItem moreMenuItem) {
        Wait().withTimeout(10, TimeUnit.SECONDS)
                .pollingEvery(1, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class)
                .ignoring(UIAssertionError.class)
                .until((WebDriver driver) -> {
                    moreMenuLink().click();
                    sleep(1000);
                    SelenideElement menu = $(By.xpath(".//div[contains(@class,'yuimenu') and contains(@style, 'display: block')]"));
                    if (menu.isDisplayed()) return menu;
                    else
                        return null;
                }).findElement(By.partialLinkText(moreMenuItem.text)).click();
        return moreMenuItem.pageObjectClass != null ? page((Class<IsPageLoaded>) moreMenuItem.pageObjectClass) : null;
    }


    public IsPageLoaded clickOnContextMenuItemOfItem(String itemLabel, int index, ContextMenuItem contextMenuItem) {
        Wait().withTimeout(10, TimeUnit.SECONDS)
                .pollingEvery(1, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class)
                .ignoring(UIAssertionError.class)
                .until((Function<WebDriver, Boolean>) driver -> {
                    //click on context menu arrow of the wanted row
                    SelenideElement row = row(itemLabel, index);
                    row.hover();
                    row.find(By.xpath(".//img[@class='menuArrowDown']")).hover().click();
                    $(By.xpath(".//div[normalize-space(@class)='yuimenu' and contains(@style,'display: block')]//a[contains(text(), '" + contextMenuItem.text + "')]")).click();
                    return true;
                });

        return contextMenuItem.pageObjectClass != null ? page((Class<? extends IsPageLoaded>) contextMenuItem.pageObjectClass) : null;
    }

    public CreateEditTrackerItemPage clickOnNewItem() {
        $(By.linkText("New Item")).click();
        return page(CreateEditTrackerItemPage.class);
    }

    public SubmitWorkItemPage clickOnNewTestRun() {
        $(By.linkText("New Test Run")).click();
        return page(SubmitWorkItemPage.class);
    }

    public TrackerItemDetailsPage openItem(String itemLabel, int index){
        row(itemLabel, index).$(By.xpath(".//a[@class='trackerItemLinkNearInlineIcon']")).click();
        return page(TrackerItemDetailsPage.class);
    }

    /**
     *
     * @param index starts from 1
     * @return
     */
    public TrackerItemDetailsPage openItem(int index){
        $$(By.xpath(".//table[@id='trackerItems']/tbody//tr")).get(index-1).$(By.xpath(".//a[@class='trackerItemLinkNearInlineIcon']")).click();
        return page(TrackerItemDetailsPage.class);
    }

    public void tickItem(int index, boolean selected) {
        $$(By.xpath(".//table[@id='trackerItems']/tbody//tr")).get(index-1).$(By.xpath(".//input[@type='checkbox']")).setSelected(selected);
    }

    /**
     * WARNING it handles only one page
     *
     * @return
     */
    public ElementsCollection getAllRows() {
        return $$(By.xpath(".//table[@id='trackerItems']/tbody/tr"));
    }

    public void checkIfNewItem(Condition condition) {
        $(By.linkText("New Item")).shouldBe(condition);
    }

    public void checkIfNewTestRun(Condition condition) {
        $(By.linkText("New Test Run")).shouldBe(condition);
    }
}
