package ru.otus.mobile.driver;

import com.codeborne.selenide.WebDriverRunner;
import com.google.inject.Injector;
import io.appium.java_client.android.AndroidDriver;
import ru.otus.mobile.config.TestContext;

public final class MobileSession {
    private final TestContext context;
    private final Injector injector;
    private final EmulatorQueue emulatorQueue;
    private final LogcatCollector logcatCollector;

    public MobileSession(
            TestContext context,
            Injector injector,
            EmulatorQueue emulatorQueue,
            LogcatCollector logcatCollector
    ) {
        this.context = context;
        this.injector = injector;
        this.emulatorQueue = emulatorQueue;
        this.logcatCollector = logcatCollector;
    }

    public void activate() {
        WebDriverRunner.setWebDriver(context.driver());
    }

    public void injectMembers(Object target) {
        injector.injectMembers(target);
    }

    public void close() {
        logcatCollector.save(context);
        AndroidDriver driver = context.driver();
        try {
            if (driver != null) {
                driver.quit();
            }
        } finally {
            WebDriverRunner.closeWebDriver();
            emulatorQueue.release(context.emulator());
        }
    }
}
