package ctbrec.ui.sites.stripchat;

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.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.StringUtil;
import ctbrec.io.HttpException;
import ctbrec.sites.stripchat.Stripchat;
import ctbrec.sites.stripchat.StripchatModel;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;
import okhttp3.Response;

public class StripchatUpdateService extends PaginatedScheduledService {

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

    private String url;
    private boolean loginRequired;
    private Stripchat stripchat;
    int modelsPerPage = 60;

    public StripchatUpdateService(String url, boolean loginRequired, Stripchat stripchat) {
        this.url = url;
        this.loginRequired = loginRequired;
        this.stripchat = stripchat;
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                List<Model> models = new ArrayList<>();
                if(loginRequired && StringUtil.isBlank(ctbrec.Config.getInstance().getSettings().username)) {
                    return Collections.emptyList();
                } else {
                    int offset = (getPage() - 1) * modelsPerPage;
                    int limit = offset + modelsPerPage;
                    String paginatedUrl = url + "&offset=" + offset + "&limit=" + limit;
                    LOG.debug("Fetching page {}", paginatedUrl);
                    if(loginRequired) {
                        SiteUiFactory.getUi(stripchat).login();
                    }
                    Request request = new Request.Builder()
                            .url(paginatedUrl)
                            .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                            .header(ACCEPT_LANGUAGE, Locale.ENGLISH.getLanguage())
                            .header(X_REQUESTED_WITH, XML_HTTP_REQUEST)
                            .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                            .build();
                    try (Response response = stripchat.getHttpClient().execute(request)) {
                        if (response.isSuccessful()) {
                            JSONObject json = new JSONObject(response.body().string());
                            if(json.has("models")) {
                                JSONArray jsonModels = json.getJSONArray("models");
                                for (int i = 0; i < jsonModels.length(); i++) {
                                    JSONObject jsonModel = jsonModels.getJSONObject(i);
                                    try {
                                        StripchatModel model = stripchat.createModel(jsonModel.getString("username"));
                                        model.setDescription("");
                                        model.setPreview(jsonModel.optString("snapshotUrl"));
                                        model.setDisplayName(model.getName());
                                        models.add(model);
                                    } catch (Exception e) {
                                        LOG.warn("Couldn't parse one of the models: {}", jsonModel, e);
                                    }
                                }
                                return models;
                            } else {
                                LOG.debug("Response was not successful: {}", json);
                                return Collections.emptyList();
                            }
                        } else {
                            throw new HttpException(response.code(), response.message());
                        }
                    }
                }
            }
        };
    }

}
