package ctbrec.ui.sites.bonga;

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.bonga.BongaCams;
import ctbrec.sites.bonga.BongaCamsModel;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;
import okhttp3.Response;

public class BongaCamsUpdateService extends PaginatedScheduledService {

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

    private BongaCams bongaCams;
    private String url;

    public BongaCamsUpdateService(BongaCams bongaCams, String url) {
        this.bongaCams = bongaCams;
        this.url = url;
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                String pageUrl = url + ((page-1) * 36);
                LOG.debug("Fetching page {}", pageUrl);
                Request request = new Request.Builder()
                        .url(pageUrl)
                        .addHeader(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                        .addHeader(ACCEPT, MIMETYPE_APPLICATION_JSON)
                        .addHeader(ACCEPT, Locale.ENGLISH.getLanguage())
                        .addHeader(REFERER, bongaCams.getBaseUrl())
                        .addHeader(X_REQUESTED_WITH, XML_HTTP_REQUEST)
                        .build();
                Response response = bongaCams.getHttpClient().execute(request);
                if (response.isSuccessful()) {
                    String content = response.body().string();
                    List<Model> models = new ArrayList<>();
                    JSONObject json = new JSONObject(content);
                    //LOG.debug(json.toString(2));
                    if (json.optString("status").equals("success")) {
                        JSONArray jsonModels = json.getJSONArray("models");
                        for (int i = 0; i < jsonModels.length(); i++) {
                            JSONObject m = jsonModels.getJSONObject(i);
                            String name = m.optString("username");
                            if (name.isEmpty()) {
                                continue;
                            }
                            BongaCamsModel model = (BongaCamsModel) bongaCams.createModel(name);
                            model.mapOnlineState(m.optString("room"));
                            model.setOnline(m.optInt("viewers") > 0);
                            model.setPreview("https:" + m.getString("thumb_image"));
                            if (m.has("display_name")) {
                                model.setDisplayName(m.getString("display_name"));
                            }
                            model.setDescription(m.optString("topic"));
                            models.add(model);
                        }
                    }
                    return models;
                } else {
                    int code = response.code();
                    response.close();
                    throw new IOException("HTTP status " + code);
                }
            }
        };
    }
}
