package ctbrec.ui.sites.bonga;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Objects;
import java.util.function.Consumer;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.sites.bonga.BongaCams;
import ctbrec.ui.ExternalBrowser;
import okhttp3.Cookie;
import okhttp3.Cookie.Builder;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public class BongaCamsElectronLoginDialog {

    private static final transient Logger LOG = LoggerFactory.getLogger(BongaCamsElectronLoginDialog.class);
    public static final String DOMAIN = "bongacams.com";
    public static final String URL = BongaCams.BASE_URL + "/login";
    private CookieJar cookieJar;
    private ExternalBrowser browser;

    public BongaCamsElectronLoginDialog(CookieJar cookieJar) throws IOException {
        this.cookieJar = cookieJar;
        browser = ExternalBrowser.getInstance();
        try {
            JSONObject config = new JSONObject();
            config.put("url", URL);
            config.put("w", 640);
            config.put("h", 480);
            JSONObject msg = new JSONObject();
            msg.put("config", config);
            browser.run(msg.toString(), msgHandler);
        } catch (InterruptedException e) {
            throw new IOException("Couldn't wait for login dialog", e);
        } finally {
            browser.close();
            browser.release();
        }
    }

    private Consumer<String> msgHandler = (line) -> {
        if(!line.startsWith("{")) {
            System.err.println(line);
        } else {
            JSONObject json = new JSONObject(line);
            //LOG.debug("Browser: {}", json.toString(2));
            if(json.has("url")) {
                String url = json.getString("url");
                if(url.endsWith("/login")) {
                    try {
                        Thread.sleep(500);
                        String username = Config.getInstance().getSettings().bongaUsername;
                        if (username != null && !username.trim().isEmpty()) {
                            browser.executeJavaScript("$('input[name=\"log_in[username]\"]').attr('value','" + username + "')");
                        }
                        String password = Config.getInstance().getSettings().bongaPassword;
                        if (password != null && !password.trim().isEmpty()) {
                            browser.executeJavaScript("$('input[name=\"log_in[password]\"]').attr('value','" + password + "')");
                        }
                        String[] simplify = new String[] {
                                "$('div#header').css('display','none');",
                                "$('div.footer').css('display','none');",
                                "$('div.footer_copy').css('display','none')",
                                "$('div[class~=\"banner_top_index\"]').css('display','none');",
                                "$('td.menu_container').css('display','none');",
                                "$('div[class~=\"fancybox-overlay\"]').css('display','none');"
                        };
                        for (String js : simplify) {
                            browser.executeJavaScript(js);
                        }
                    } catch(Exception e) {
                        LOG.warn("Couldn't auto fill username and password for BongaCams", e);
                    }
                }

                if(json.has("cookies")) {
                    JSONArray _cookies = json.getJSONArray("cookies");
                    for (int i = 0; i < _cookies.length(); i++) {
                        JSONObject cookie = _cookies.getJSONObject(i);
                        if(cookie.getString("domain").contains(DOMAIN)) {
                            Builder b = new Cookie.Builder()
                                    .path(cookie.getString("path"))
                                    .domain(DOMAIN)
                                    .name(cookie.getString("name"))
                                    .value(cookie.getString("value"))
                                    .expiresAt(Double.valueOf(cookie.optDouble("expirationDate")).longValue());
                            if(cookie.optBoolean("hostOnly")) {
                                b.hostOnlyDomain(DOMAIN);
                            }
                            if(cookie.optBoolean("httpOnly")) {
                                b.httpOnly();
                            }
                            if(cookie.optBoolean("secure")) {
                                b.secure();
                            }
                            Cookie c = b.build();
                            cookieJar.saveFromResponse(HttpUrl.parse(BongaCams.BASE_URL), Collections.singletonList(c));
                        }
                    }
                }

                try {
                    URL _url = new URL(url);
                    if (Objects.equals(_url.getPath(), "/")) {
                        browser.close();
                    }
                } catch (MalformedURLException e) {
                    LOG.error("Couldn't parse new url {}", url, e);
                } catch (IOException e) {
                    LOG.error("Couldn't send shutdown request to external browser", e);
                }
            }
        }
    };
}
