package com.clanstop.healing.locator;

import org.openqa.selenium.By;

/**
 * Converts Selenium {@link By} locators to and from a ({@code type}, {@code value}) pair
 * so they can be persisted in {@code locator_history} and rebuilt later.
 */
public final class Locators {

    private Locators() {}

    /** @return a two-element array {type, value}, e.g. {"id", "username"}. */
    public static String[] split(By by) {
        String s = by.toString();               // e.g. "By.id: username"
        int sep = s.indexOf(": ");
        String type = sep > 0 ? s.substring(0, sep) : s;
        String value = sep > 0 ? s.substring(sep + 2) : "";
        if (type.startsWith("By.")) {
            type = type.substring(3);
        }
        return new String[]{type, value};
    }

    public static String typeOf(By by)  { return split(by)[0]; }
    public static String valueOf(By by) { return split(by)[1]; }

    /** Rebuild a {@link By} from a persisted (type, value) pair. */
    public static By build(String type, String value) {
        return switch (type) {
            case "id"              -> By.id(value);
            case "name"            -> By.name(value);
            case "cssSelector"     -> By.cssSelector(value);
            case "xpath"           -> By.xpath(value);
            case "className"       -> By.className(value);
            case "tagName"         -> By.tagName(value);
            case "linkText"        -> By.linkText(value);
            case "partialLinkText" -> By.partialLinkText(value);
            default -> throw new IllegalArgumentException("Unknown locator type: " + type);
        };
    }
}
