package cz.moneta.test.dsl.hypos.pages.contract.approval;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.hypos.components.Menu;
import cz.moneta.test.dsl.hypos.pages.HyposPageFlow;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.hypos.HyposEndpoint;
import cz.moneta.test.harness.support.web.Click;
import cz.moneta.test.harness.support.web.CustomAction;
import cz.moneta.test.harness.support.web.Lookup;
import cz.moneta.test.harness.support.web.Wait;
import org.openqa.selenium.WebElement;

import java.util.ArrayList;
import java.util.List;

import static cz.moneta.test.dsl.hypos.pages.contract.approval.ApVerificationPage.AVAILABLE_DOCUMENT;

@Wait(AVAILABLE_DOCUMENT)
public interface ApVerificationPage extends HyposPageFlow<ApVerificationPage>, StoreAccessor, Menu {
    String SEND_TO_AP_BUTTON = "//a[text()='Odeslat']";
    String AVAILABLE_DOCUMENT = "//tbody[@id='risk-docs']/tr[1]";
    String AVAILABLE_TASKS = "//tbody[@id='complaints']/tr";
    String AVAILABLE_TASK = AVAILABLE_TASKS + "[%s]";
    String AVAILABLE_TASK_ID = AVAILABLE_TASK + "//input[@class='task-id']/preceding-sibling::a";

    String TASK_IDS = "TASK_IDS";

    @Click(SEND_TO_AP_BUTTON)
    ApVerificationPage clickSendToApButton();

    @CustomAction
    default ApVerificationPage dragAndDropDocuments() {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        endpoint.waitForElementsToLoad(5, AVAILABLE_TASKS);
        List<WebElement> availableTasks = endpoint.findAndGetListOfElements(AVAILABLE_TASKS, Lookup.XPATH);
        for (int i = 1; i <= availableTasks.size(); i++) {
            String availableTask = String.format(AVAILABLE_TASK, i);
            endpoint.waitForElementsToLoad(5, availableTask);
            endpoint.dragAndDrop(AVAILABLE_DOCUMENT, availableTask);
        }
        return null;
    }

    @CustomAction
    default ApVerificationPage getTaskIds(Harness harness) {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        List<String> taskIds = new ArrayList<>();
        endpoint.waitForElementsToLoad(5, AVAILABLE_TASKS);
        List<WebElement> availableTasks = endpoint.findAndGetListOfElements(AVAILABLE_TASKS, Lookup.XPATH);
        for (int i = 1; i <= availableTasks.size(); i++) {
            String availableTask = String.format(AVAILABLE_TASK_ID, i);
            taskIds.add(endpoint.getText(availableTask));
        }
        harness.store(TASK_IDS, taskIds);
        return null;
    }
}