package ru.otus.mobile.config;

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

public final class MobileConfig {
    private final String appPackage;
    private final String appUrl;
    private final String reservationOwnerUsername;
    private final List<Emulator> emulators;

    public MobileConfig(
            String appPackage,
            String appUrl,
            String reservationOwnerUsername,
            List<Emulator> emulators
    ) {
        this.appPackage = appPackage;
        this.appUrl = appUrl;
        this.reservationOwnerUsername = reservationOwnerUsername;
        this.emulators = List.copyOf(emulators);
    }

    public String appPackage() {
        return appPackage;
    }

    public String appUrl() {
        return appUrl;
    }

    public String reservationOwnerUsername() {
        return reservationOwnerUsername;
    }

    public List<Emulator> emulators() {
        return emulators;
    }

    public record Emulator(String id, String appiumUrl, String deviceName, String appUrl) {
        public static List<Emulator> parse(String rawValue, String defaultAppUrl) {
            List<Emulator> emulators = new ArrayList<>();
            for (String entry : rawValue.split(",")) {
                String trimmed = entry.trim();
                if (trimmed.isEmpty()) {
                    continue;
                }
                String[] parts = trimmed.split("\\|");
                String id = parts.length > 0 ? parts[0].trim() : "emulator-1";
                String appiumUrl = parts.length > 1 ? parts[1].trim() : "http://localhost:4723";
                String deviceName = parts.length > 2 ? parts[2].trim() : "Android Emulator";
                String emulatorAppUrl = parts.length > 3 ? parts[3].trim() : defaultAppUrl;
                emulators.add(new Emulator(id, appiumUrl, deviceName, emulatorAppUrl));
            }
            if (emulators.isEmpty()) {
                emulators.add(new Emulator("emulator-1", "http://localhost:4723", "Android Emulator", defaultAppUrl));
            }
            return emulators;
        }
    }
}
