package cz.moneta.test.dsl.ufo.operations.shared;

import cz.moneta.test.harness.endpoints.ufo.UfoEndpoint;
import cz.moneta.test.harness.support.web.Lookup;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UfoOpsUtils {

    private static final String TABLE_CELL_XPATH = "//td[@class='ufo-Table-BodyCell' and text()='%s']";

    public static float getScoreTableValueFloat(boolean useApplicationScore, int siblingIndex, UfoEndpoint endpoint) {
        return Float.parseFloat(removeSpaces(getScoreTableValueString(useApplicationScore, siblingIndex, endpoint)));
    }

    public static String getScoreTableValueString(boolean useApplicationScore, int siblingIndex, UfoEndpoint endpoint) {
        String rowFirstCellText = getScoreRowFirstCellText(useApplicationScore);
        return getTableValueString(rowFirstCellText, siblingIndex, endpoint);
    }

    public static float getTableValueFloat(String rowFirstCellXpath, int siblingIndex, UfoEndpoint endpoint) {
        return Float.parseFloat(removeSpaces(getTableValueString(rowFirstCellXpath, siblingIndex, endpoint)));
    }

    public static String getTableValueString(String rowFirstCellText, int siblingIndex, UfoEndpoint endpoint) {
        return getCellValue(getTableCellXpath(rowFirstCellText), siblingIndex, endpoint);
    }

    private static String getScoreRowFirstCellText(boolean useApplicationScore) {
        return useApplicationScore ? "Application Score Total" : "Behavioral Score";
    }

    public static String getTableCellXpath(String cellText) {
        return String.format(TABLE_CELL_XPATH, cellText);
    }

    private static String getCellValue(String rowFirstCellXpath, int siblingIndex, UfoEndpoint endpoint) {
        return endpoint.getText(rowFirstCellXpath + String.format("//following-sibling::td[%s]", siblingIndex), Lookup.XPATH);
    }

    private static String removeSpaces(String input) {
        return input.replace(" ", "");
    }

    public static List<String> loadClientsIcoFromTextFile(String textFilePath) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(textFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
}