package ctbrec.ui.sites.jasmin;

import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

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

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.sites.jasmin.LiveJasmin;
import ctbrec.sites.jasmin.LiveJasminModel;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.Request;

public class LiveJasminUpdateService extends PaginatedScheduledService {

    private static final Logger LOG = LoggerFactory.getLogger(LiveJasminUpdateService.class);
    private String url;
    private LiveJasmin liveJasmin;

    public LiveJasminUpdateService(LiveJasmin liveJasmin, String url) {
        this.liveJasmin = liveJasmin;
        this.url = url;
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                // sort by popularity
                var cookieJar = liveJasmin.getHttpClient().getCookieJar();
                var sortCookie = new Cookie.Builder()
                        .domain(LiveJasmin.baseDomain)
                        .name("listPageOrderType")
                        .value("most_popular")
                        .build();
                cookieJar.saveFromResponse(HttpUrl.parse("https://" + LiveJasmin.baseDomain), Collections.singletonList(sortCookie));

                // TODO find out how to switch pages
                LOG.debug("Fetching page {}", url);
                var request = new Request.Builder()
                        .url(url)
                        .addHeader(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                        .addHeader(ACCEPT, MIMETYPE_APPLICATION_JSON)
                        .addHeader(ACCEPT_LANGUAGE, Locale.ENGLISH.getLanguage())
                        .addHeader(REFERER, liveJasmin.getBaseUrl())
                        .addHeader(X_REQUESTED_WITH, XML_HTTP_REQUEST)
                        .build();
                try (var response = liveJasmin.getHttpClient().execute(request)) {
                    LOG.debug("Response {} {}", response.code(), response.message());
                    if (response.isSuccessful()) {
                        var body = response.body().string();
                        List<Model> models = new ArrayList<>();
                        var json = new JSONObject(body);
                        if(json.optBoolean("success")) {
                            parseModels(models, json);
                        } else if(json.optString("error").equals("Please login.")) {
                            var siteUI = SiteUiFactory.getUi(liveJasmin);
                            if(siteUI.login()) {
                                return call();
                            } else {
                                LOG.error("Request failed:\n{}", body);
                                throw new IOException("Response was not successful");
                            }
                        } else {
                            LOG.error("Request failed:\n{}", body);
                            throw new IOException("Response was not successful");
                        }
                        return models;
                    } else {
                        throw new HttpException(response.code(), response.message());
                    }
                }
            }
        };
    }

    private void parseModels(List<Model> models, JSONObject json) {
        var data = json.getJSONObject("data");
        var content = data.getJSONObject("content");
        var performers = content.getJSONArray("performers");
        for (var i = 0; i < performers.length(); i++) {
            var m = performers.getJSONObject(i);
            var name = m.optString("pid");
            if(name.isEmpty()) {
                continue;
            }
            LiveJasminModel model = (LiveJasminModel) liveJasmin.createModel(name);
            model.setId(m.getString("id"));
            model.setPreview(m.getString("profilePictureUrl"));
            model.setOnlineState(LiveJasminModel.mapStatus(m.optInt("status")));
            models.add(model);
        }
    }
}
