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

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import com.intland.codebeamer.functionaltest.page.BasePage;
import org.openqa.selenium.By;
import java.util.HashMap;
import java.util.Map;

import static com.codeborne.selenide.Condition.disappear;
import static com.codeborne.selenide.Condition.exist;
import static com.codeborne.selenide.Condition.visible;
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 TrackersPage extends BasePage {

    public SelenideElement leftPane(){return $("#west");}
    public SelenideElement leftTreePane(){return leftPane().$("#treePane");}

    public enum TrackerTypes {
        EPICS("Epics"),
        REQUIREMENTS("Requirements"),
        USER_STORIES("User Stories"),
        TASKS("Tasks"),
        BUGS("Bugs"),
        TEST_RUN("Test Run"),
        TEST_RUNS("Test Runs");

        private final String text;

        TrackerTypes(String s) {
            text = s;
        }

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

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

    public NewTrackerPage clickOnNewTracker() {
        $("a[title*='New Tracker']").click();
        return page(NewTrackerPage.class);
    }

    public TrackerItemListPage clickOnTracker(TrackerTypes trackerType) {
        $(By.linkText(trackerType.text)).should(exist).doubleClick();
        return page(TrackerItemListPage.class);
    }

    public TrackerItemListPage clickOnTracker(String trackerName) {
        waitForPageToLoad();
        actions().moveToElement($(By.linkText(trackerName)).should(exist)).doubleClick().perform();
        return page(TrackerItemListPage.class);
    }

    public TrackerItemListPage openTrackerFromLeftTree(String trackerName){
        leftTreePane().find(By.xpath(".//a[text()='" + trackerName + "']")).doubleClick();
        TrackerItemListPage trackerItemListPage = page(TrackerItemListPage.class);
        for (int i = 0; i < 5; ++i) {
            if (!trackerItemListPage.isPageLoaded()){
                openTrackerFromLeftTree(trackerName);
            }
        }
        return trackerItemListPage;
    }

    public String getTrackerId(String trackerName) {
        return leftPane().$(By.partialLinkText(trackerName)).parent().getAttribute("id");
    }

    public TrackerConfigurationPage navigateToTrackerConfigurationPage(String trackerName) {
        $(By.xpath(".//div[@id='west']/div[@id='treePane']//a[contains(text(),'" + trackerName + "')]")).should(exist).contextClick();
        $(By.linkText("Customize")).waitUntil(visible, 60000).click();
        return page(TrackerConfigurationPage.class);
    }

    public int getWorkItemsCount() {
        return leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Work Items')]]//li[not(contains(@class, 'jstree-hidden'))]")).size();
    }

    public int getConfigItemsCount() {
        return leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Config Items')]]//li[not(contains(@class, 'jstree-hidden'))]")).size();
    }

    public int getOpenItemsCountOf(String trackerName){
        return Integer.parseInt(leftPane().$(By.xpath(".//a[text()='"+ trackerName+"']/following-sibling::span/b")).getText());
    }

//    public int getAllItemsCountOf(TrackersPage.TrackerTypes workItemType){
//        return Integer.parseInt($(byXpath(".//td[./a[contains(text(), '"+ workItemType +"')]]/following-sibling::td[3]/a[2]")).getText());
//    }

    public int getOpenWorkItemsCountSum() {
        int sum = 0;
        ElementsCollection openItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Work Items')]]//li[not(contains(@class, 'jstree-hidden'))]/span/b"));
        for (SelenideElement openItem : openItems) {
            sum += Integer.parseInt(openItem.text());
        }
        return sum;
    }

    public int getAllWorkItemsCountSum() {
        int sum = 0;
        ElementsCollection closedItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Work Items')]]//li[not(contains(@class, 'jstree-hidden'))]/span[@class='trackerItemStat']"));
        for (SelenideElement closeItem : closedItems) {
            sum += Integer.parseInt(closeItem.text().split("/")[1].trim());
        }
        return sum;
    }

    public int getAllConfigItemsCountSum() {
        int sum = 0;
        ElementsCollection closedItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Config Items')]]//li[not(contains(@class, 'jstree-hidden'))]/span[@class='trackerItemStat']"));
        for (SelenideElement closeItem : closedItems) {
            sum += Integer.parseInt(closeItem.text().split("/")[1].trim());
        }
        return sum;
    }

    public int getOpenConfigItemsCountSum() {
        int sum = 0;
        ElementsCollection openItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Config Items')]]//li[not(contains(@class, 'jstree-hidden'))]/span/b"));
        for (SelenideElement openItem : openItems) {
            sum += Integer.parseInt(openItem.text());
        }
        return sum;
    }

    public Map<String, String> getAllTrackerIds(){
        Map<String, String> result = new HashMap();
        ElementsCollection workItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Work Items')]]//li[not(contains(@class, 'jstree-hidden'))]"));
        ElementsCollection configItems = leftTreePane().findAll(By.xpath(".//li[./a[contains(text(), 'Config Items')]]//li[not(contains(@class, 'jstree-hidden'))]"));

        for (SelenideElement tracker : workItems){
            result.put(tracker.$(By.xpath("./a")).getText(), tracker.getAttribute("id"));
        }

        for (SelenideElement tracker : configItems){
            result.put(tracker.$(By.xpath("./a")).getText(), tracker.getAttribute("id"));
        }

        return result;
    }

    public void waitForWidgetToLoad() {
        $(".loaderImage").waitUntil(disappear, 60000);
    }

    public void waitForLeftTreeToLoad() {
        $("#j1_loading").waitUntil(disappear, 60000);
    }

    public void waitForDashboardToLoad() {
        $("#dashboardLoadingIndicator").waitUntil(disappear, 60000);
        waitForWidgetToLoad();
    }

    public boolean isNewTrackerHidden() {
        return $$("a[title*='New Tracker']").isEmpty();
    }

    public void checkIfTracker(String trackerName, Condition condition){
        leftTreePane().find(By.xpath(".//a[text()='" + trackerName + "']")).shouldBe(condition);
    }

    public void checkIfNewTracker(Condition condition) {
        $("a[title*='New Tracker']").shouldBe(condition);
    }

    @Override
    public void waitForPageToLoad() {
        super.waitForPageToLoad();
        waitForLeftTreeToLoad();
        waitForDashboardToLoad();
    }

    public boolean isTrackerVisible(String trackerName) {
        return $(By.linkText(trackerName)).is(visible);
    }
}
