package ctbrec.ui.sites.bonga;

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.bonga.BongaCams;
import ctbrec.sites.bonga.BongaCamsHttpClient;
import ctbrec.ui.TabProvider;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.sites.AbstractSiteUi;

public class BongaCamsSiteUi extends AbstractSiteUi {

    private static final transient Logger LOG = LoggerFactory.getLogger(BongaCamsSiteUi.class);
    private BongaCamsTabProvider tabProvider;
    private BongaCamsConfigUI configUi;
    private BongaCams bongaCams;

    public BongaCamsSiteUi(BongaCams bongaCams) {
        this.bongaCams = bongaCams;
        tabProvider = new BongaCamsTabProvider(bongaCams);
        configUi = new BongaCamsConfigUI(bongaCams);
    }

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

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

    @Override
    public synchronized boolean login() throws IOException {
        boolean automaticLogin = bongaCams.login();
        if(automaticLogin) {
            return true;
        } else {
            BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>();
            try {
                new Thread(() -> {
                    // login with external browser window
                    try {
                        new BongaCamsElectronLoginDialog(bongaCams.getHttpClient().getCookieJar());
                    } catch (Exception e1) {
                        LOG.error("Error logging in with external browser", e1);
                        Dialogs.showError("Login error", "Couldn't login to " + bongaCams.getName(), e1);
                    }

                    try {
                        queue.put(true);
                    } catch (InterruptedException e) {
                        LOG.error("Error while signaling termination", e);
                    }
                }).start();
                queue.take();
            } catch (InterruptedException e) {
                LOG.error("Error while waiting for login dialog to close", e);
                throw new IOException(e);
            }

            BongaCamsHttpClient httpClient = (BongaCamsHttpClient)bongaCams.getHttpClient();
            boolean loggedIn = httpClient.checkLoginSuccess();
            if(loggedIn) {
                LOG.info("Logged in. User ID is {}", httpClient.getUserId());
            } else {
                LOG.info("Login failed");
            }
            return loggedIn;
        }
    }
}
