package ctbrec.ui.sites.amateurtv;

import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.util.ArrayList;
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.sites.amateurtv.AmateurTv;
import ctbrec.sites.amateurtv.AmateurTvModel;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;

public class AmateurTvUpdateService extends PaginatedScheduledService {

    private static final Logger LOG = LoggerFactory.getLogger(AmateurTvUpdateService.class);
    private static final int ITEMS_PER_PAGE = 50;

    private AmateurTv site;
    private String url;

    public AmateurTvUpdateService(AmateurTv site, String url) {
        this.site = site;
        this.url = url;
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                return loadModelList();
            }

        };
    }

    private List<Model> loadModelList() throws IOException {
        int offset = page - 1;
        String pageUrl = url + '/' + offset * ITEMS_PER_PAGE + '/' + ITEMS_PER_PAGE + "/es";
        LOG.debug("Fetching page {}", pageUrl);
        var request = new Request.Builder()
                .url(pageUrl)
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(ACCEPT, Locale.ENGLISH.getLanguage())
                .header(REFERER, site.getBaseUrl())
                .build();
        try (var response = site.getHttpClient().execute(request)) {
            if (response.isSuccessful()) {
                var content = response.body().string();
                List<Model> models = new ArrayList<>();
                var json = new JSONObject(content);
                var modelNodes = json.getJSONObject("cams").getJSONArray("nodes");
                parseModels(modelNodes, models);
                return models;
            } else {
                int code = response.code();
                throw new IOException("HTTP status " + code);
            }
        }
    }

    private void parseModels(JSONArray jsonModels, List<Model> models) {
        for (var i = 0; i < jsonModels.length(); i++) {
            var m = jsonModels.getJSONObject(i);
            var user = m.getJSONObject("user");
            var name = user.optString("username");
            AmateurTvModel model = (AmateurTvModel) site.createModel(name);
            model.setPreview(m.optString("imageURL"));
            model.setDescription(m.optJSONObject("topic").optString("text"));
            models.add(model);
        }
    }
}
