package ctbrec.ui.sites.showup;

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.showup.Showup;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.sites.AbstractSiteUi;
import ctbrec.ui.tabs.TabProvider;

public class ShowupSiteUi extends AbstractSiteUi {

    private static final Logger LOG = LoggerFactory.getLogger(ShowupSiteUi.class);

    private Showup site;
    private ConfigUI configUi;
    private TabProvider tabProvider;

    public ShowupSiteUi(Showup site) {
        this.site = site;
        configUi = new ShowupConfigUI(site);
        tabProvider = new ShowupTabProvider(site);
    }

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

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

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

                    try {
                        queue.put(true);
                    } catch (InterruptedException e) {
                        LOG.error("Error while signaling termination", e);
                        Thread.currentThread().interrupt();
                    }
                }).start();
                queue.take();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IOException(e);
            }

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

}
