package ctbrec.sites.jasmin;

import java.io.IOException;
import java.util.NoSuchElementException;

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

import ctbrec.Config;
import ctbrec.io.HttpClient;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LiveJasminHttpClient extends HttpClient {

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

    protected LiveJasminHttpClient() {
        super("livejasmin");
    }

    @Override
    public synchronized boolean login() throws IOException {
        if (loggedIn) {
            return true;
        }

        boolean cookiesWorked = checkLoginSuccess();
        if (cookiesWorked) {
            loggedIn = true;
            LOG.debug("Logged in with cookies");
            return true;
        }

        return false;
    }

    public boolean checkLoginSuccess() throws IOException {
        OkHttpClient temp = client.newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .build();

        String url = "https://m.livejasmin.com/en/member/favourite/get-favourite-list?ajax=1";
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", Config.getInstance().getSettings().httpUserAgentMobile)
                .addHeader("Accept", "application/json, text/javascript, */*")
                .addHeader("Accept-Language", "en")
                .addHeader("Referer", LiveJasmin.BASE_URL)
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .build();
        try(Response response = temp.newCall(request).execute()) {
            LOG.debug("Login Check {}: {} - {}", url, response.code(), response.message());
            if(response.isSuccessful()) {
                return true;
            } else {
                return false;
            }
        }
    }

    public String getSessionId() {
        Cookie sessionCookie = getCookieJar().getCookie(HttpUrl.parse(LiveJasmin.BASE_URL), "session");
        if(sessionCookie != null) {
            return sessionCookie.value();
        } else {
            throw new NoSuchElementException("session cookie not found");
        }
    }
}
