package com.intland.codebeamer.functionaltest.page.common;
import com.codeborne.selenide.Condition;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.ui.ExpectedConditions;

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 EditorComponent implements IsPageLoaded {

    public WYSIWYGTab wysiwygTab = new WYSIWYGTab();
    public MarkupTab markupTab = new MarkupTab();

    @Override
    public boolean isPageLoaded() throws UnsupportedOperationException {
        try {
            Wait().withTimeout(5, TimeUnit.SECONDS)
                    .ignoring(NoSuchElementException.class)
                    .until(ExpectedConditions.visibilityOf($(".ditch-tab-pane-wrap")));
        }catch(Exception e){
            return false;
        }
        return true;
    }

    @Override
    public void waitForPageToLoad() {
        $(".ditch-tab-pane-wrap").waitUntil(Condition.visible, 5000);
    }

    public enum Tab {
        WYSIWYG(".//div[contains(@id, 'wysiwyg-tab')]", WYSIWYGTab.class),
        MARKUP(".//div[contains(@id, 'markup-tab')]", MarkupTab.class),
        PREVIEW(".//div[contains(@id, 'preview-tab')]", PreviewTab.class);

        private final String selector;
        public final Class<?> pageObjectClass;

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

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

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

    public Object clickOnTab(Tab tab) {
        $(By.xpath(tab.selector)).click();
        sleep(2000);//wait for tab to load properly
        return page(tab.pageObjectClass);
    }

}
