package ctbrec.ui.sites.cam4;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.sites.ConfigUI;
import ctbrec.sites.cam4.Cam4;
import ctbrec.sites.cam4.Cam4HttpClient;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.sites.AbstractSiteUi;
import ctbrec.ui.tabs.TabProvider;
import javafx.application.Platform;

public class Cam4SiteUi extends AbstractSiteUi {
    private static final transient Logger LOG = LoggerFactory.getLogger(Cam4SiteUi.class);

    private Cam4TabProvider tabProvider;
    private Cam4ConfigUI configUI;
    private Cam4 cam4;

    public Cam4SiteUi(Cam4 cam4) {
        this.cam4 = cam4;
        tabProvider = new Cam4TabProvider(cam4);
        configUI = new Cam4ConfigUI(cam4);
    }

    @Override
    public TabProvider getTabProvider() {
        return tabProvider;
    }

    @Override
    public ConfigUI getConfigUI() {
        return configUI;
    }

    @Override
    public synchronized boolean login() throws IOException {
        boolean automaticLogin = cam4.login();
        if (automaticLogin) {
            return true;
        } else {

            BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>();

            Runnable showDialog = () -> {
                // login with external browser
                try {
                    new Cam4ElectronLoginDialog(cam4.getHttpClient().getCookieJar());
                } catch (Exception e1) {
                    LOG.error("Error logging in with external browser", e1);
                    Dialogs.showError("Login error", "Couldn't login to " + cam4.getName(), e1);
                }

                try {
                    queue.put(true);
                } catch (InterruptedException e) {
                    LOG.error("Error while signaling termination", e);
                }
            };

            Platform.runLater(showDialog);
            try {
                queue.take();
            } catch (InterruptedException e) {
                LOG.error("Error while waiting for login dialog to close", e);
                throw new IOException(e);
            }

            Cam4HttpClient httpClient = (Cam4HttpClient) cam4.getHttpClient();
            boolean loggedIn = httpClient.checkLoginSuccess();
            return loggedIn;
        }
    }
}
